JPGygax68
5/7/2016 - 4:36 PM

Check/assert whether a class has a method with a given signature.

Check/assert whether a class has a method with a given signature.

#include <iostream>
#include <string>

class A {
public:
    void method1();
    void method2(int);
    static void method3(int []);
};

#define HAS_METHOD(Class, MethodName, ReturnType, ...) (std::is_same<ReturnType (Class::*)(__VA_ARGS__), decltype(&Class::MethodName)>::value)
#define HAS_STATIC_METHOD(Class, MethodName, ReturnType, ...) (std::is_same<ReturnType (*)(__VA_ARGS__), decltype(&Class::MethodName)>::value)

#define ASSERT_METHOD(Class, MethodName, ReturnType, ...) \
    static_assert(HAS_METHOD(Class, MethodName, ReturnType, __VA_ARGS__), "Class does not have required method or method has wrong signature")
#define ASSERT_STATIC_METHOD(Class, MethodName, ReturnType, ...) \
    static_assert(HAS_STATIC_METHOD(Class, MethodName, ReturnType, __VA_ARGS__), "Class does not have required method or method has wrong signature")
    
int main()
{
    ASSERT_METHOD(A, method1, void,);
    ASSERT_METHOD(A, method2, void, int);
    ASSERT_STATIC_METHOD(A, method3, void, int[]);
    
    std::cout << "method1: " << (HAS_METHOD       (A, method1, void,      ) ? "yes" : "no")  << std::endl;
    std::cout << "method2: " << (HAS_METHOD       (A, method2, void, int  ) ? "yes" : "no")  << std::endl;
    std::cout << "method3: " << (HAS_STATIC_METHOD(A, method3, void, int[]) ? "yes" : "no")  << std::endl;
    
    std::cout << std::endl << "Press RETURN to terminate" << std::endl;
    char dummy; std::cin >> std::noskipws >> dummy;

    return 0;
}