问题描述
我只在代码块中的 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'
解决方法
您的 GCC 版本不支持 if constexpr
。版本 7 中添加了支持。
可以查询支持哪些C++17特性on the GCC website;与此问题相关的行是“constexpr if”。在支持每个特性的第一个版本的列中有很多“7”——甚至一个“8”,所以你应该期待 C++17 支持在版本 6 系列的编译器中参差不齐(例如您的 6.3.0)。