C++ Logo

STD-PROPOSALS

Advanced search

Subject: [std-proposals] operator ==/!= for empty struct
From: Dawid Kurek (dawikur_at_[hidden])
Date: 2019-11-03 05:58:39


I'm using `std::variant` with structs as events. Structs are often empty.

E.g
#include <variant>

struct Exit {
    bool operator== (Exit) const { return true; }
    bool operator!= (Exit) const { return false; }
};

struct Reload{
    bool operator== (Reload) const { return true; }
    bool operator!= (Reload) const { return false; }
};

using Msg = std::variant<Exit, Reload>;

extern Msg Update();

void foo() {
    Msg msg;
    do {
       msg = Update();
        // ...
    } while (msg != Msg{Exit{}});
}

This approach requires that all those tag structs in `variant` has
`operator==` or `operator!=` (depending on the check).

This is not a hard limitation but adds a lot of additional and repetitive code.
It can be minimized with inheritance (base class with those operators)
or macro.

The idea is that operator ==/!= for empty structs could be generated
automatically by the compiler.

So the code would look like:
#include <variant>

struct Exit {};
struct Reload {};

using Msg = std::variant<Exit, Reload>;

extern Msg Update();

void foo() {
    Msg msg;
    do {
       msg = Update();
        // ...
    } while (msg != Msg{Exit{}});
}

[Sub]idea would be to generate complementary operator,
if struct/class provides operator ==, generate not-equal by negating
the result of
equal and vice versa.

Thanks for any comments!
Dawid


STD-PROPOSALS list run by herb.sutter at gmail.com

Standard Proposals Archives on Google Groups