为什么这不与gcc48和clang32编译?为什么编译错误与enable_if
#include <type_traits>
template <int N>
struct S {
template<class T>
typename std::enable_if<N==1, int>::type
f(T t) {return 1;};
template<class T>
typename std::enable_if<N!=1, int>::type
f(T t) {return 2;};
};
int main() {
S<1> s1;
return s1.f(99);
}
GCC错误:
/home/lvv/p/sto/test/t.cc:12:2: error: no type named ‘type’ in ‘struct enable_if<false, int>’
f(T t) {return 2;};
^
CLANG错误:
/home/lvv/p/sto/test/t.cc:11:26: error: no type named 'type' in 'std::enable_if<false, int>'; 'enable_if' cannot be used to
disable this declaration
typename std::enable_if<N!=1, int>::type
^~~~
/home/lvv/p/sto/test/t.cc:16:7: note: in instantiation of template class 'S<1>' requested here
S<1> s1;
^
编辑 - 解决方案:
我接受的答案,从查尔斯丹参,但实际原因我无法使用建议的解决方法(专门针对N)。我找到了适用于我的其他解决方法。让enable_if
取决于T
:
typename std::enable_if<(sizeof(T),N==1), int>::type
你确定这是去反正工作?你不能仅仅通过它们的返回类型来重载方法(除非'enable_if'被实现为一种语言结构,而不是像我现在所假设的那样实现一个简单的模板化类)。 – zneak
为什么使enable_if的解决方法完全依赖于T所必需的? –
该解决方案对我无效!我得到了'错误:没有匹配的调用函数...' –