enable_if和转换操作员?
-
28-09-2019 - |
题
有机会使用的机会 enable_if
与类型转换操作员?似乎很棘手,因为返回类型和参数列表都是隐式的。
解决方案
dixit 文档:
似乎没有一种方法来指定转换操作员的启用器。但是,转换构造函数可以将推动器作为额外的默认参数。
其他提示
从我所做的小研究(忽略约翰内斯的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;
}
为了记录,我对此感到沮丧几天,直到我意识到自己想要 enable_if
不是针对Sfinae,而是用于编译时行为的变化。您可能还会发现这是您需要的真正原因 enable_if
还。只是一个建议。
(请注意,这是C ++ 98 ERA的答案)
尽管我可以理解这个问题的理论兴趣,但我个人避免了尽可能多地使用转换操作员。
我唯一使用的一致性的是转换为伪树立(使用安全的布尔习惯),用于智能彩音或代理,正如我所指出的那样,我实际上使用了一个技巧来防止完整的布尔语义...
如果我想促进转化,我更喜欢沿线的东西:
template <class T>
T to() const;
它不受转换操作员的局限性(按签名)的限制,需要明确调用,只是因为它更清楚。
实际上,我找到了一种方法。我们使用私人,未使用的课程来标记不应该存在的转换,我们使用 boost::mpl::if_
选择是产生转换为Noconversion还是所需的类型。
class A {
class NoConversion { };
template<class B> operator typename boost::mpl::if_<Cond, B, NoConversion>::type() const;
}
不隶属于 StackOverflow