【发布时间】:2020-01-17 18:09:57
【问题描述】:
我只是在 C++ 中使用 std::enable_if 尝试使用 SFINAE。我以为我理解了理论部分,直到我无法编译以下代码。更令人困惑的是 Visual Studio 和 Linux 上的不同行为。只要您不取消注释(Calculator<int> cInt;),此粘贴的代码就会在 VS 上编译。但是,使用 GCC 它会给我编译错误。我已经在 STL 实现中看到了这种代码,我真的期待更多标准化的实现无处不在。无论如何,您能否在这里检查并提出我的理解存在哪些差距?
template<typename T>
class Calculator
{
public:
typename enable_if<is_arithmetic<T>::value, T>::type
addition(T a, T b)
{
return a + b;
}
typename enable_if<!is_arithmetic<T>::value, T>::type
addition(T a, T b)
{
cout << "Default\n";
return a;
}
};
void SFINAE()
{
// Calculator<int> cInt;
}
int main ()
{
SFINAE();
return 0;
}
GCC 8.1 的错误日志: j
doodle.cpp:30:3: error: 'typename std::enable_if<(! std::is_arithmetic<_Tp>::value), T>::type Calculator<T>::addition(T, T)' cannot be overloaded with 'typename std::enable_if<std::is_arithmetic<_Tp>::value, T>::type Calculator<T>::addition(T, T)'
addition(T a, T b)
^~~~~~~~
jdoodle.cpp:25:3: note: previous declaration 'typename std::enable_if<std::is_arithmetic<_Tp>::value, T>::type Calculator<T>::addition(T, T)'
addition(T a, T b)
当您使用 int 取消注释 Calculator 类初始化时,VS 上的错误日志:
sfinae.h(17): error C3646: 'addition': unknown override specifier
sfinae.h(17): error C2059: syntax error: '('
sfinae.h(18): error C2334: unexpected token(s) preceding '{'; skipping apparent function body
【问题讨论】:
标签: c++ c++11 templates template-meta-programming sfinae