Any chance to use enable_if
with a type conversion operator? Seems tricky, since both return type and parameters list are implicit.
From the little research I did (and ignoring the c++0x comment from Johannes), my answer is that it depends what you want the enable_if
for. If you want the conversion operation to T
to exist or not from the type T
then it seems that the answer is no, there is no way in C++03 (as Ugo said). But if you need the enable_if
to change the behavior of the operator depending on the type of T
then yes, there is a workaround which is to call an enabled helper function (called to
as Matthieu suggested).
#include
#include
#include
struct B{
B(const B& other){}
B(){}
};
struct A{
template
T to(typename boost::enable_if_c::value, void*>::type = 0){
std::clog << "converted to non class" << std::endl;
return T(0);
}
template
T to(typename boost::enable_if_c::value, void*>::type = 0){
std::clog << "conveted to class" << std::endl;
return T();
}
template
operator T(){
return to();
}
};
int main(){
A a;
double d = (double)a; // output: "converted to non class"
B b = (B)(a); // output: "converted to class"
return 0;
}
For the record, I was frustrated with this for several days, until I realized that I wanted enable_if
not for SFINAE but for compile-time behavior change. You may also find that this is the real reason for your need for enable_if
also. Just a suggestion.
(Please note that this is an answer for the C++98 era)