Calling a free function instead of a method if it doesn't exist

前端 未结 4 853
滥情空心
滥情空心 2021-02-01 07:33

Suppose you have a family of type-unrelated classes implementing a common concept by means of a given method returning a value:

class A { public: int val() const         


        
4条回答
  •  感情败类
    2021-02-01 08:01

    Use this type trait class to determine whether a type has got val member function.

    template
    struct has_val {
        typedef char yes;
        typedef struct { char c[2]; } no;
    
        template
        static constexpr auto test(int) -> decltype( std::declval().val(), yes() );
    
        template
        static constexpr no test(...);
    
        static constexpr bool value = sizeof(test(0)) == sizeof(yes);
    };
    

    You can use it as a condition to enable_if.

提交回复
热议问题