Detecting Member Function Presence Using C 11 Type Traits
Question:
How can we determine if a class possesses a member function with a specific signature without requiring the class to provide it?
Elaboration of the Dilemma:
The problem arises when we need to perform custom operations based on the presence or absence of a particular member function in a class. Unlike cases where the class must provide the function, we seek a method to discern its existence for conditional processing. The ideal solution avoids global function overwriting, excessive stack invocations, and intrusive namespace declarations.
Template-Based Solution:
Utilizing C 11 type traits, we can devise a template function that verifies the existence of the target function:
template<typename C, typename Ret, typename... Args> struct has_serialize { // Assertion to prevent instantiation with non-function arguments static_assert( std::integral_constant<T, false>::value, "Second template parameter needs to be of function type." ); // Specialization to perform the check private: template<typename T> static constexpr auto check(T*) -> typename std::is_same< decltype( std::declval<T>().serialize( std::declval<Args>()... ) ), Ret // ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ >::type; // attempt to call it and see if the return type is correct template<typename> static constexpr std::false_type check(...); typedef decltype(check<C>(0)) type; public: static constexpr bool value = type::value; };
Usage:
We can now employ the has_serialize template to verify function existence within a class:
struct X { int serialize(const std::string&) { return 42; } }; struct Y : X {}; std::cout << has_serialize<X, int(const std::string&)>::value; // prints 1
In the example above, has_serialize
The above is the detailed content of How Can C 11 Type Traits Detect the Presence of a Member Function with a Specific Signature?. For more information, please follow other related articles on the PHP Chinese website!