我最近遇到了一些编译器错误,归结为以下虚拟示例。基本上我正在构建一个“plus2”函数模板,我希望它只适用于 int 和 float .从逻辑上讲,当“is_numerical”类型特征测试通过时,程序只会加 2。然而,它在编译时挂起并出现错误 C2782/C2784/C2676,提示将 2 添加到 string。
例子仅供引用,没有意义。更重要的是,编写这种逻辑的正确方法是什么?谢谢。
#include <iostream>
#include <string>
using namespace std;
template <typename T>
struct is_numerical {
static const bool value = false;
};
template <>
struct is_numerical<float> {
static const bool value = true;
};
template <>
struct is_numerical<int> {
static const bool value = true;
};
template <typename T>
T plus2(T input) {
if (is_numerical<T>::value) {
return input + 2;
} else { return input; }
}
int main()
{
//char x('a'); // prints 'a'
string x("a"); // compiler error
cout << plus2(x) << endl;
return 0;
}
最佳答案
问题是,当 T input
是一个 std::string
时,您仍在尝试编译 return input + 2;
. 即使它在始终为 false
的 if 语句中。
在 C++17 中,if constexpr
允许条件编译代码。
template <typename T>
T plus2(T input) {
if constexpr (is_numerical<T>::value) {
return input + 2;
} else { return input; }
}
在 C++ 的所有标准版本中,SFINAE还可以防止无效代码被编译。
template <typename T>
T plus2(T input, typename std::enable_if<! is_numerical<T>::value>::type* = 0) {
return input;
}
template <typename T>
T plus2(T input, typename std::enable_if<is_numerical<T>::value>::type* = 0) {
return input + 2;
}
关于C++ 类型特征虚拟示例 : compiler error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48118663/