Home >Backend Development >C++ >How Can I Check for the Existence of a Non-Member `operator==` in C ?
In C , checking for the existence of a member function operator== is straightforward using the provided member function. However, determining the presence of a non-member operator== can prove more challenging.
C 03 Method:
The following technique can be employed to check for the existence of any operator:
namespace CHECK { class No { bool b[2]; }; template<typename T, typename Arg> No operator== (const T&, const Arg&); bool Check (...); No& Check (const No&); template <typename T, typename Arg = T> struct EqualExists { enum { value = (sizeof(Check(*(T*)(0) == *(Arg*)(0))) != sizeof(No)) }; }; }
To use this method, simply invoke the EqualExists template:
CHECK::EqualExists<A>::value;
If the EqualExists value is non-zero, the non-member operator== exists.
C 11 Method:
C 11 provides a cleaner approach using decltype and std::declval:
namespace CHECK { struct No {}; template<typename T, typename Arg> No operator== (const T&, const Arg&); template<typename T, typename Arg = T> struct EqualExists { enum { value = !std::is_same<decltype(std::declval<T>() < std::declval<Arg>()), No>::value }; }; }
To check for the non-member operator==, use:
CHECK::EqualExists<A>::value;
The above is the detailed content of How Can I Check for the Existence of a Non-Member `operator==` in C ?. For more information, please follow other related articles on the PHP Chinese website!