Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is std::variant permitted to hold the same type more than once?

Tags:

c++

What can be the use case of std::variant holding the same type more than once?

Refer to https://en.cppreference.com/w/cpp/utility/variant

You can only find the issue when you start to call std::get<T>(v).

like image 847
Bowen Fu Avatar asked Jun 24 '21 02:06

Bowen Fu


1 Answers

Say we want to represent a token that can be a keyword, an identifier, or a symbol. One possible implementation is thus:

enum TokenType : std::size_t {
    Keyword = 0, Identifier = 1, Symbol = 2
};

using Token = std::variant<std::string, std::string, char>;

Now it is possible to use, for example:

std::get<TokenType::Keyword>(token)

to access the alternatives.

Whether this is a good idea is of course up for debate, but it does show the existence of such use cases.

like image 84
L. F. Avatar answered Sep 20 '22 11:09

L. F.