NeomerArcana
NeomerArcana

Reputation: 2311

How to add to std::variants?

So I have:

typedef std::variant<int,float,std::string> VarType;

And I want to be able to do:

VarType a = 1;
VarType b = 1;
VarType c = a + b;

When the types are mixed, it's cool for it to throw.

Upvotes: 2

Views: 717

Answers (1)

Vittorio Romeo
Vittorio Romeo

Reputation: 93384

VarType c = std::get<int>(a) + std::get<int>(b);

More general:

VarType c = std::visit([](auto x, auto y) -> VarType 
                       { 
                           if constexpr(!std::is_same_v<decltype(x), decltype(y)>)
                           {
                               throw;
                           }
                           else
                           {
                               return x + y; 
                           }
                       }, a, b);

live example on wandbox.org

Upvotes: 4

Related Questions