C++ 编译错误|由于编译器解析器,无法编译cpp程序
简短描述C++ 编译错误|由于编译器解析器,无法编译cpp程序,c++,c++11,C++,C++11,简短描述 我试图编译一个简短的lambda,将给定的输入转换为字符串格式。我的整个类使用一个模板,即模板。我想重载如果constexpr,至少需要C++17才能使用 使用if constexpr可以编写如下内容 if constexpr ( std::is_same_v<T, std::string> ) return value else { // something else that return a std::string } 如果const
我试图编译一个简短的lambda,将给定的输入转换为字符串格式。我的整个类使用一个模板,即模板。我想重载如果constexpr,至少需要C++17才能使用
使用if constexpr
可以编写如下内容
if constexpr ( std::is_same_v<T, std::string> )
return value
else
{
// something else that return a std::string
}
如果constexpr(std::is_same_v)
返回值
其他的
{
//返回std::string的其他内容
}
只有这样,当T
不是std::string
时,才可以从编译返回值中排除,否则将else
大小写的正文排除
注意,我使用了std::is_same
类型特征来检查T
和std::string
是否是相同的类型<代码>std::is_same
是由编译器决定编译时间的东西。您的typeid(…).value()
是一个运行时值。建议:如果可能,优先选择编译时类型特征
但是我需要看一个更完整的例子来说明如何在类/结构中使用if constexpr
在C++17之前,您需要两个不同的函数来初始化tostring
谢谢您的输入!我只能在这个项目中使用cpp11。@Drio-所以你必须开发不同的功能。你应该展示更多关于你的类的东西。如果constexpr是为这种情况设计的,那么这就是,但是你需要使用C++17
//Let T = int, value = 12, so the below parameter equals, int value, which holds the value of 12.
toString = [](T value) -> std::string {
if (typeid(std::string).name() == typeid(T).name())
{ //should failed since typeid(int).name != typeid(std::string).name
return value;
}
//do some stuff to convert the date into a string
return; // return the final 'value' in string format.
};
//However, when the compiler parses the code, it thinks that I am trying to return value, which is of type int. But the function is supposed to return a string.
//In reality, this should not happen since my if statement will take care of it.
if constexpr ( std::is_same_v<T, std::string> )
return value
else
{
// something else that return a std::string
}