Check if a class has a member function of a given signature

后端 未结 17 1492
無奈伤痛
無奈伤痛 2020-11-22 03:00

I\'m asking for a template trick to detect if a class has a specific member function of a given signature.

The problem is similar to the one cited here http://www.go

17条回答
  •  梦毁少年i
    2020-11-22 03:27

    Here is a simpler take on Mike Kinghan's answer. This will detect inherited methods. It will also check for the exact signature (unlike jrok's approach which allows argument conversions).

    template 
    class HasGreetMethod
    {
        template 
        static std::true_type testSignature(void (T::*)(const char*) const);
    
        template 
        static decltype(testSignature(&T::greet)) test(std::nullptr_t);
    
        template 
        static std::false_type test(...);
    
    public:
        using type = decltype(test(nullptr));
        static const bool value = type::value;
    };
    
    struct A { void greet(const char* name) const; };
    struct Derived : A { };
    static_assert(HasGreetMethod::value, "");
    

    Runnable example

提交回复
热议问题