c++operator-overloadingruntime-compilation

Blocking operator==() at compile time


I have an ID-Record class and I want to block callers / users from using the operator== since it is ambiguous (user may want to compare only data field for equality).

Here's my class:

#include <string>
#include <functional>

class ID_Record
{
  public:
    bool operator==(const ID_Record& other) const
        {  throw std::bad_function_call(); }
    unsigned int id;  // Record ID used for database.
    std::string  value;
};

I would prefer to have operator==() "blocked" at compile time, so the compiler can catch it rather than at runtime.

The compiler should generate an error for this code:

ID_Record a(6, "Tree");
ID_Record b(3, "Platinum");
if (a == b) std::cout "Records are equal\n"; // This line should fail compilation.

I want to block cases of compiler generated functionality also.


Solution

  • Since C++11, you can explicitly declare any class method/operator with = delete to prevent it from being callable, eg:

    class ID_Record
    {
      public:
        bool operator==(const ID_Record& other) const = delete;
        unsigned int id;  // Record ID used for database.
        std::string  value;
    };
    

    Online Demo

    If code tries to invoke the deleted operator== in any way, the compile will fail with an error message, such as:

    error: use of deleted function ‘bool ID_Record::operator==(const ID_Record&) const’

    On the other hand, if you simply omit the operator== completely, eg:

    class ID_Record
    {
      public:
        unsigned int id;  // Record ID used for database.
        std::string  value;
    };
    

    Online Demo

    Then you will also get a (different) compile error, such as:

    error: no match for ‘operator==’ (operand types are ‘ID_Record’ and ‘ID_Record’)

    The compiler will not generate a default operator== for you, unless you explicitly ask for it via = default in C++20 and later.