This Q is an extension of:
Is it possible to write a C++ template to check for a function's existence?
Is there any utility which will help to find:
- If a member name exists inside a class or not? This member can be a variable or a method.
- Specifying the type of the member should be optional
For non-C++17:
Boost Type Traits library has metafunctions for both checking if member with given name present or more fine grained control by giving signature.
Following is a program using slightly modified
HAS_MEMBER
macro:As noted in linked page it uses the fact that if you inherit from two classes that have members with same name, attempts to use this name will become ambiguous.
With
std::experimental::is_detected
andstd::experimental::disjunction
you could do this:Then you would use
has_foo<my_class>::value
in whatever you want.The above will work for more than just types and member functions, but you could easily constrain it by using traits like
std::is_member_function_pointer
andstd::is_member_object_pointer
if you like.To supply your optional argument, you could use the
std::experimental::is_detected_exact
helper.Live Demo
Note that if you take the implementations of the above traits from the pages I linked, you can use this with C++14. A minor change to the
disjunction
code will let you use it in C++11.C++03
Usage: Simply invoke the macro with whatever member you want to find:
Now we can utilize
HasMember_X
to checkX
in ANYclass
as below:Catches:
class
must not have overloaded methods. If it has then this trick fails. i.e. even though the named member is present more than once, the result will befalse
.B
is base ofS
&void B::Bar ()
is present, thenHasMember_Bar<S, void (B::*)()>::value
orHasMember_Bar<S, void (S::*)()>::value
orHasMember_Bar<S>::value
will givefalse