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

后端 未结 17 1479
無奈伤痛
無奈伤痛 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条回答
  •  长发绾君心
    2020-11-22 03:10

    Building on jrok's answer, I have avoided using nested template classes and/or functions.

    #include 
    
    #define CHECK_NESTED_FUNC(fName) \
        template > \
        struct _has_##fName \
        : public std::false_type {}; \
        \
        template  \
        struct _has_##fName().fName(std::declval()...))>> \
        : public std::is_same().fName(std::declval()...)), Ret> \
        {}; \
        \
        template  \
        using has_##fName = _has_##fName;
    
    #define HAS_NESTED_FUNC(Class, Func, Signature) has_##Func::value
    

    We can use the above macros as below:

    class Foo
    {
    public:
        void Bar(int, const char *) {}
    };
    
    CHECK_NESTED_FUNC(Bar);  // generate required metafunctions
    
    int main()
    {
        using namespace std;
        cout << boolalpha
             << HAS_NESTED_FUNC(Foo, Bar, void(int, const char *))  // prints true
             << endl;
        return 0;
    }
    

    Suggestions are welcome.

提交回复
热议问题