C++ Logo

std-proposals

Advanced search

operator ==/!= for empty struct

From: Dawid Kurek <dawikur_at_[hidden]>
Date: Sun, 3 Nov 2019 12:58:39 +0100
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

Received on 2019-11-03 06:01:07