C++ Logo

STD-PROPOSALS

Advanced search

Subject: Re: [std-proposals] operator ==/!= for empty struct
From: Dawid Kurek (dawikur_at_[hidden])
Date: 2019-11-03 06:19:31


Hi,

Yes, you are right. I admit the whole idea is just to make life a bit
easier and make the syntax prettier:
    msg != Msg{Exit{}}
vs
    holds_alternative<Exit>(msg)
I like nice, simple syntax, what can I say... ;)

Other thing I would like to have is operator==/!= (variant, T) to push
it even step further to
    msg != Exit{}
which plays nicely when the struct isn't empty:
    struct KeyPress { char key; };
    using msg = std::variant<Exit, Reload, KeyPress>;
    if (msg == KeyPress{'p'})

but this is completely separate thread.

Regards,
Dawid

niedz., 3 lis 2019 o 13:08 Oleg Fatkhiev <ogfatog_at_[hidden]> napisał(a):
>
> Hello,
> Looks like for this concrete example you just need to use holds_alternative instead of equals operator. And you don't need to create comparison operators at all!
>
> Best regards,
> Oleg
>
> On Sun, Nov 3, 2019, 12:58 Dawid Kurek via Std-Proposals <std-proposals_at_[hidden]> wrote:
>>
>> 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 mailing list
>> Std-Proposals_at_[hidden]
>> https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals


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

Standard Proposals Archives on Google Groups