【问题标题】:Why does using "constexpr" give primary expression error in codeblocks [closed]为什么使用“constexpr”会在代码块中给出主要表达式错误[关闭]
【发布时间】:2025-12-16 11:25:01
【问题描述】:

仅在代码块中,我在 constexpr 之前得到预期的主要表达式。有没有办法来解决这个问题?这是我要测试的代码。我已将 c++ 17 设置为编译器。我正在使用 GNU GCC 编译器。 GCC (MinGW.org GCC-6.3.0-1) 6.3.0。我在 Visual Studio 中没有收到此错误。

#include <iostream>
#include <vector>

template<class T>
void testType(std::vector<T> &x)
{
    if constexpr (std::is_same_v<T, std::string>)
    {
        //push string
        std::cout<<"String\n";
    }
    else if constexpr (std::is_same_v<T,int>)
    {
        //push integer
        std::cout<<"int\n";
    }
}
int main()
{
    
    std::vector<std::string> x;
    
    testType(x);

    return 0;
}

这是我遇到的错误。

error: expected primary-expression before 'constexpr'
error: expected ')' before 'constexpr'

【问题讨论】:

  • 您是否尝试将#include &lt;type_traits&gt; 添加到您的代码中?
  • 你的 GCC 版本是多少?
  • @AdrianMole 是的,我试过了。
  • 添加缺少的#include &lt;type_traits&gt; 后,显示的代码使用 gcc 10 编译时不会出现任何错误。gcc 6 可能太旧,无法完全支持 C++17。
  • 从 GCC 7.1 开始工作。对不起,伙计,是时候更新了。如果可以更新。示例:godbolt.org/z/qq86eE

标签: c++ gcc c++17 gcc6


【解决方案1】:

您的 GCC 版本不支持 if constexpr。版本 7 中添加了支持。

您可以查看支持哪些 C++17 功能on the GCC website;与此问题相关的行是“constexpr if”。在支持每个功能的第一个版本的列中有很多“7”——甚至一个“8”,所以你应该期望版本 6 系列的编译器对 C++17 的支持参差不齐(例如你的 6.3.0)。

【讨论】:

    最近更新 更多