c++ - enable_if 和转换运算符?

标签 c++ boost casting operator-overloading enable-if

有没有机会将 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/

相关文章:

c++ - 发布版本中会删除 "if ... ASSERT"吗?

C++ 如何在 Boost Global Logger 上设置严重性过滤器

mysql - 在同一调用中将列转换为不同类型

sql - 如何删除不能转换为 INT 的行

postgresql - Postgis 查询 ST_Intersects 与 GeoJSON (jsonb)

python - 通过 SWIG 传递函数指针数组

c++ - 这个 C++ 初始化有效吗?

c++ - 调试命令行应用程序

c++ - 将 boost::variant 传递给(来自)dll 是否安全?

c++ - boost::bind 为具有默认值的成员函数?