【发布时间】:2012-12-07 12:24:48
【问题描述】:
为什么这不能用 gcc48 和 clang32 编译?
#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;
^
编辑 - 解决方案
我已接受 Charles Salvia 的回答,但出于实际原因,我无法使用建议的解决方法(专门研究 N)。我找到了其他适合我的解决方法。使enable_if 依赖于T:
typename std::enable_if<(sizeof(T),N==1), int>::type
【问题讨论】:
-
您确定这仍然可以工作吗?您不能仅通过方法的返回类型来重载方法(除非
enable_if是作为一种语言结构实现的,而不是像我目前假设的那样通过一个简单的模板类实现)。 -
为什么使 enable_if 依赖于 T 的解决方法是必要的,究竟是什么?
-
该解决方案对我不起作用!我得到了
error: no matching function for call ... -
@LiDong - 我的解决方案?这就是你否决这个问题的原因?我在这里问一个问题。答案请看下面。
-
@LeonidVolnitsky
sizeof(T)在我的情况下不起作用。很抱歉投反对票。那时我只是沮丧。我在 C++11 中使用了默认模板参数。
标签: c++ templates metaprogramming sfinae enable-if