uj2*_*uj2 13 c++ boost casting operator-overloading enable-if
有机会使用enable_if
类型转换运算符吗?看起来很棘手,因为返回类型和参数列表都是隐式的.
从我做的小研究(并忽略约翰内斯的c ++ 0x评论),我的答案是它取决于你想要的东西enable_if
.如果你希望转换操作T
存在或不存在,T
那么似乎答案是否定的,C++ 03中没有办法(正如Ugo所说).但是如果您需要根据类型然后enable_if
更改运算符的行为,T
则有一种解决方法是调用启用的辅助函数(称为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;
}
Run Code Online (Sandbox Code Playgroud)
为了记录,我对此感到沮丧了好几天,直到我意识到我enable_if
不想要SFINAE,而是为了编译时的行为改变.您可能还会发现这也是您需要的真正原因enable_if
.只是一个建议.
(请注意,这是C++ 98时代的答案)
归档时间: |
|
查看次数: |
4236 次 |
最近记录: |