Home > Backend Development > C++ > How Can I Check for the Existence of a Non-Member `operator==` in C ?

How Can I Check for the Existence of a Non-Member `operator==` in C ?

Mary-Kate Olsen
Release: 2024-12-02 16:50:11
Original
878 people have browsed it

How Can I Check for the Existence of a Non-Member `operator==` in C  ?

Checking for the Existence of 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&amp;, const Arg&amp;);

  bool Check (...);
  No&amp; Check (const No&amp;);

  template <typename T, typename Arg = T>
  struct EqualExists
  {
    enum { value = (sizeof(Check(*(T*)(0) == *(Arg*)(0))) != sizeof(No)) };
  };  
}
Copy after login

To use this method, simply invoke the EqualExists template:

CHECK::EqualExists<A>::value;
Copy after login
Copy after login

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&amp;, const Arg&amp;);

  template<typename T, typename Arg = T>
  struct EqualExists
  {
    enum { value = !std::is_same<decltype(std::declval<T>() < std::declval<Arg>()), No>::value };
  };  
}
Copy after login

To check for the non-member operator==, use:

CHECK::EqualExists<A>::value;
Copy after login
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template