Skip to content

Instantly share code, notes, and snippets.

@JPGygax68
Last active September 18, 2017 19:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JPGygax68/e98e6f0727a12d4e06b00eb9c87d7b51 to your computer and use it in GitHub Desktop.
Save JPGygax68/e98e6f0727a12d4e06b00eb9c87d7b51 to your computer and use it in GitHub Desktop.
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;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment