[英]How to use enable_if in a class obj?
The code below is OK: 下面的代码可以:
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
}
But when I use a class to bundle them, it can not be compiled: 但是,当我使用一个类将它们捆绑在一起时,无法对其进行编译:
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++ print: lang ++打印:
error: functions that differ only in their return type cannot be overloaded
So I write something to cheat to the compiler(add an S in second foo
): 所以我写了一些要欺骗编译器的东西(在第二个
foo
添加一个S):
template <class S>
std::enable_if<tmp::is_sequence<T>::value, bool>
foo(T t) { return false; }
It still can not work: 它仍然无法工作:
error: no type named 'type' in 'std::enable_if<false, bool>'
How can I make it work in a class? 如何在课堂上使用它?
Both member-functions should have different template parameter (following will work ok) 两种成员函数都应具有不同的模板参数(下面的方法可以正常工作)
template <class T>
class test {
public:
template<typename U>
typename std::enable_if<std::is_atomic<U>::value, bool>::type
foo(U t) { return true; }
template<typename U>
typename std::enable_if<tmp::is_sequence<U>::value, bool>::type
foo(U t) { return false; }
};
如果您真的想做自己想做的事情,那么经典的成语就是引入一个带有默认值的伪SFINAE参数:
bool foo(T t, std::enable_if<..., void*> = nullptr) { ... }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.