It is easy to write a template that will detect the presence of a specific element in a type using void_t :
#include <type_traits> // This comes from cppreference template<typename... Ts> struct make_void { typedef void type;}; template<typename... Ts> using void_t = typename make_void<Ts...>::type; // primary template handles types that have no ::aMember template< class T, class = void_t<> > struct has_aMember : std::false_type { }; // specialization recognizes types that do have a ::aMember template< class T > struct has_aMember<T, void_t<decltype( T::aMember )>> : std::true_type { };
Now, if I want to determine if any other element is present, I would have to copy-paste the detector templates and simply change aMember to otherMember :
template< class T, class = void_t<> > struct has_otherMember : std::false_type { }; template< class T > struct has_otherMember<T, void_t<decltype( T::otherMember )>> : std::true_type { };
I would like to avoid this copy and pass the member name as a parameter to a more general version of the discovery pattern:
template< class T, class member, class = void_t<> > struct has_arbitrary_member : std::false_type { }; template< class T, class member > struct has_arbitrary_member<T, void_t<decltype( T::member )>> : std::true_type { };
so that I can use this has_arbitrary_member , passing the type and name of the member as a template parameter:
std::cout << has_arbitrary_member<MyType, aMember>(); std::cout << has_arbitrary_member<MyType, otherMember>();
However, with the definition above, this will not compile. Is there any other way to implement such functionality?
c ++ c ++ 11 templates c ++ 14
Rostislav
source share