Croper 发表于 2020-1-16 17:16:50

(C++奇技淫巧)如何在编译期间检测两个类型之间是否能进行某种运算。

本帖最后由 Croper 于 2020-1-16 17:33 编辑

翻了半天的boost库总结出来的,把hana::is_valid翻写了一个容易理解点的版本:
以“==”操作为例:
using namespace std;
template <typename T1,typename T2>
struct CanEqual{
private:
        template <typename =decltype(declval<T1>()==declval<T2>())>
        constexpr static auto answer(int) { return true; };
        constexpr static auto answer(...) { return false; };
public:
        constexpr operator bool(){
                return answer(0);
        }
};

测试:struct Test1 {};//没有任何转换函数

struct Test2 {
        bool operator==(int) const; //能够与int进行==操作
};


int main() {
        constexpr bool a = CanEqual<int, int>();//true
        constexpr bool b = CanEqual<double, int>();//true
        constexpr bool c = CanEqual<string, int>();//false
        constexpr bool d = CanEqual<Test1, int>();//false
        constexpr bool e = CanEqual<Test2, int>();//true
}
页: [1]
查看完整版本: (C++奇技淫巧)如何在编译期间检测两个类型之间是否能进行某种运算。