At the moment, I'm using this method to check if a class has a method with a specific signature.
After attending Walter E. Brown's metaprogramming CppCon2014 talk, I started wondering if void_t
could be used in this particular situation to make the code cleaner and more readable.
However I'm having trouble thinking in terms of void_t
- so far I understand that void_t
can help me determine at compile-time whether or not an expression is valid.
Example:
template< class, class = void >
struct has_type_data_member : false_type { };
template< class T >
struct has_type_data_member<T, void_t<decltype(T::data)>> : true_type { };
If decltype(T::type)
is a valid expression, has_type_data_member<T>
will be a true compile-time constant. Therefore, we are sure that T
has a member field called data
.
I want to use the same approach to check if a type T
has a method with a particular name and a particular signature.
Let's say I want to check if T
has a method called getCount()
that returns int
. This is what I expected to work ((Ideone.com link)):
template< class, class = void >
struct hasGetCount : false_type { };
template< class T >
struct hasGetCount<T, VoidT<decltype(T::getCount)>>
: std::is_same<decltype(std::declval<T>().getCount()), int>::type { };
Unfortunately, the static_assert
tests do not pass.
What am I doing wrong? Is it possible to use void_t
in this situation?
Bonus questions:
- How can I also check if the method signature is equal to a signature the user passes as in the original implementation?
I can use macros to define these kind of helper structs like this:
DEFINE_METHOD_CHECKER(hasGetCount, getCount); // ... static_assert(hasGetCount<ClassWithGetCount>::value == true, "");
Is it possible to avoid having to define a
struct
first then check the struct's value? I mean, is it possible to use a macro to write something like this? Example:static_assert(CHECK_METHOD(ClassWithGetCount, getCount)::value == true, "");
decltype
. – Terbium