enable_if和转换运算符?

uj2*_*uj2 13 c++ boost casting operator-overloading enable-if

有机会使用enable_if类型转换运算符吗?看起来很棘手,因为返回类型和参数列表都是隐式的.

alf*_*lfC 8

从我做的小研究(并忽略约翰内斯的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时代的答案)


log*_*og0 2

dixit文档
似乎没有办法为转换运算符指定启用程序。但是,转换构造函数可以将启动器作为额外的默认参数。

  • 对于 C++11,情况不再如此。请参阅http://stackoverflow.com/questions/18100297/how-can-i-use-stdenable-if-in-a-conversion-operator (3认同)