Type trait: Check if class have specific function (maybe inherit)

前端 未结 3 1062
心在旅途
心在旅途 2021-01-05 07:49

I know that there are many possible ways to detect if a class has a specific function but non of them really work for my exact case. My current implementation to check for t

3条回答
  •  有刺的猬
    2021-01-05 08:32

    Here is a way to do it (work for your 4 test cases, did not test it intensively though), thanks @Jarod42 for the improvement (see initial answer at the end):

    template 
    int call_foo (int (T::*)(float));
    
    template 
    std::true_type has_foo(decltype(call_foo(&C::foo)));
    
    template 
    std::false_type has_foo (...);    
    
    template
    using HasFoo = decltype(has_foo(0));
    

    The problem with your code was that you were expecting U::* whereas &B::foo is A::* (not B::*). Here I let the compiler choose the value of T by using implicit type deduction so I don't run into such issue.

    The code works as follow:

    • If T does not have a foo member, then the compiler will choose the second overload of has_foo.
    • If T does have a foo member, the compiler will try the first overload but will fail since there is no matching call_foo function so it will again choose the second one and make a std::false_type.

    Working code on ideone: http://ideone.com/erh93I.

    You can put everything in a class if you want:

    template 
    class HasFoo {
    
        template 
        static int call_foo (int (C::*)(float));
    
        template 
        static std::true_type has_foo (decltype(call_foo(&C::foo)));
    
        template 
        static std::false_type has_foo (...);
    
    public:
        static constexpr bool value = decltype(has_foo(0)){};
    };
    

提交回复
热议问题