有没有机会将 enable_if
与类型转换运算符一起使用?看起来很棘手,因为返回类型和参数列表都是隐式的。
最佳答案
根据我所做的小研究(并忽略 Johannes 的 c++0x 评论),我的回答是这取决于您想要什么 enable_if
为了。如果要转换操作为T
存在与否来自类型T
那么似乎答案是否定的,在 C++03 中没有办法(正如 Ugo 所说)。但如果您需要 enable_if
根据 T
的类型更改运算符(operator)的行为那么是的,有一种解决方法是调用启用的辅助函数(称为 to<T>
,正如 Matthieu 建议的那样)。
#include<iostream>
#include<boost/utility/enable_if.hpp>
#include<boost/type_traits/is_class.hpp>
struct B{
B(const B& other){}
B(){}
};
struct A{
template<class T>
T to(typename boost::enable_if_c<not boost::is_class<T>::value, void*>::type = 0){
std::clog << "converted to non class" << std::endl;
return T(0);
}
template<class T>
T to(typename boost::enable_if_c<boost::is_class<T>::value, void*>::type = 0){
std::clog << "conveted to class" << std::endl;
return T();
}
template<class T>
operator T(){
return to<T>();
}
};
int main(){
A a;
double d = (double)a; // output: "converted to non class"
B b = (B)(a); // output: "converted to class"
return 0;
}
为了记录,我为此沮丧了好几天,直到我意识到我想要 enable_if
不是为了 SFINAE,而是为了编译时行为改变。您可能还会发现这是您需要 enable_if
的真正原因。还。只是一个建议。
(请注意这是针对C++98时代的答案)
关于c++ - enable_if 和转换运算符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3076206/