Check if class has function with signature

后端 未结 3 539
遇见更好的自我
遇见更好的自我 2020-12-21 17:31

There are other answers on this site using SFINAE but with non C++11 code, and there are others using C++11 code like decltypes to make this process easier. However, I am no

3条回答
  •  时光说笑
    2020-12-21 18:05

    There is help with macros:

    #define DEFINE_METHOD_CHECKER(RETURN_TYPE, METHOD_NAME, PARAMETERS)     \
    template                                                    \
    struct Is ## METHOD_NAME ## MemberFunctionExists                        \
    {                                                                       \
    private:                                                                \
        typedef char True;                                                  \
        typedef char (&False)[2];                                           \
        template\
        struct Checker                                                      \
        {                                                                   \
            typedef True Type;                                              \
        };                                                                  \
        template                                                \
        static typename Checker::Type Tester(const U*);                  \
        static False Tester(...);                                           \
    public:                                                                 \
        enum { value = (sizeof(Tester(static_cast(0))) == sizeof(True)) }; \
    }
    
    // IsMethodMemberFunctionExists::value
    DEFINE_METHOD_CHECKER(int, Method, (bool));
    // IsTestMemberFunctionExists::value
    DEFINE_METHOD_CHECKER(int*, Test, (int&, char));
    
    #include 
    
    class Exists
    {
    public:
        int Method(bool);
        int* Test(int&, char);
    
    };
    
    class NotExists
    {
    };
    
    int main()
    {
        std::cout << IsMethodMemberFunctionExists::value << std::endl;
        std::cout << IsTestMemberFunctionExists::value << std::endl;
    
        std::cout << IsMethodMemberFunctionExists::value << std::endl;
        std::cout << IsTestMemberFunctionExists::value << std::endl;
    }
    

    So, in your case you need to define a few checkers - one checker for one type of Event:

    // void recieve(const Event1&)
    DEFINE_METHOD_CHECKER(void, recieve, (const Event1&));
    
    // void recieve(const Event2&)
    DEFINE_METHOD_CHECKER(void, recieve, (const Event2&));
    

提交回复
热议问题