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, "");
First, an id-expression naming a nonstatic member function can't be used as an unevaluated operand (such as the operand of
decltype
). Moreover, you should check for whether the entire function call expression is well formed, not just whether there is a member calledgetCount
:(Use
declval<T&>
if you want to check thatgetCount()
can be called on an lvalue.)If you just check for the existence of a
getCount
member, then you get a hard error if a member with that name exists but isn't callable (e.g., a data member).Although at this point you might as well consider just using something like
instead of writing the
decltype
twice.You could use
void_t
to easily verify that the return type ofgetCount
is convertible toint
:(Ideone live code)
Hopefully, by the time C++17 comes out, we'll be able to do this more easily with Concepts Lite: