【发布时间】:2013-11-07 05:38:16
【问题描述】:
下面的代码是可以的:
template <class T>
std::enable_if<std::is_atomic<T>::value, bool>
foo(T t) { return true; }
template <class T>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }
int main(void){
foo(1); // return true
auto std::vector<int> a{2};
foo(a); // return false
}
但是当我使用一个类来捆绑它们时,却无法编译:
template <class T>
class test {
public:
std::enable_if<std::is_atomic<T>::value, bool>
foo(T t) { return true; }
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }
};
int main(...) {
test<int> obj;
obj.foo(1);
test<std::vector<int>> obj2;
std::vector<int> tmp{2};
obj2.foo(tmp);
}
clang++ 打印:
error: functions that differ only in their return type cannot be overloaded
所以我写了一些东西来欺骗编译器(在第二个foo添加一个S):
template <class S>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }
还是不行:
error: no type named 'type' in 'std::enable_if<false, bool>'
如何让它在课堂上发挥作用?
【问题讨论】:
-
嗯。什么库公开
std::Enable_if?还是你的意思是std::enable_if? -
@WhozCraig 对拼写错误感到抱歉
-
您正在尝试将 SFINAE 应用于不是函数模板的内容。那是行不通的。
T不是推论出来的 - 它在你专攻test的那一刻就已经确定了。对于给定的test<X>,该类有两个普通(非模板)成员函数,都带有签名bool foo(X)。
标签: c++ class c++11 overloading enable-if