Detect operator support with decltype/SFINAE

前端 未结 5 1871
夕颜
夕颜 2020-12-05 01:12

A (somewhat) outdated article explores ways to use decltype along with SFINAE to detect if a type supports certain operators, such as == or &

5条回答
  •  离开以前
    2020-12-05 02:07

    You need to make your less_than_test function a template, since SFINAE stands for Substitution Failure Is Not An Error and there's no template function that can fail selection in your code.

    template 
    struct supports_less_than
    {
        template 
        static auto less_than_test(const U* u) -> decltype(*u < *u, char(0))
        { }
    
        static std::array less_than_test(...) { }
    
        static const bool value = (sizeof(less_than_test((T*)0)) == 1);
    };
    
    int main()
    {
        std::cout << std::boolalpha << supports_less_than::value << endl;
    }
    

提交回复
热议问题