Checking for a Class Member Function of a Given Signature
Consider the challenge of verifying whether a class possesses a specific member function of a predetermined signature. While related to the concept discussed in Scott Meyers' Effective C Third Edition, this problem requires a distinct solution.
The Problem and Requirement
Unlike Meyers' scenario where ensuring the existence of a member function is crucial for compilation, this situation demands a flexible approach. The objective is to distinguish between classes that implement the desired member function and those that do not, triggering different actions accordingly.
A Template Solution
C 11 provides a template-based solution that effectively detects member functions, even those inherited. The provided implementation relies on the is_same trait to check for return type compatibility:
#include <type_traits> // Check member function presence and return type correctness template<typename C, typename Ret, typename... Args> struct has_serialize { static constexpr bool value = std::is_same< decltype( std::declval<T>().serialize( std::declval<Args>()... ) ), Ret >::type::value; };
Usage
To utilize this approach, simply specify the class to check, along with the member function's return type and arguments:
struct X { int serialize(const std::string&) { return 42; } }; std::cout << has_serialize<Y, int(const std::string&)>::value; // prints 1
The above is the detailed content of Does My Class Have This Member Function?. For more information, please follow other related articles on the PHP Chinese website!