Skip to content

Trivia impact: rare

The Variant With Two Ints

two indistinguishable alternatives, yet a legal variant

std::variant<int, int> value(std::in_place_index<1>, 42);
std::cout << value.index() << ' ' << std::get<1>(value) << '\n';

Does a variant require all of its alternative types to differ?

Answer
1 42

Duplicate alternatives are legal; the index selects the second int.

Why

std::variant<int, int> has two alternatives even though they share a type. [variant.get] permits std::get<I> to select by index, while the type form std::get<T> requires T to occur exactly once. Building this entry with -DSHOW_BUG made GCC 11.5 reject std::get<int>(value) with static assertion failed: T must occur exactly once in alternatives.

Where it shows up

It is mainly useful to code generators or protocol code that wants two distinct positions with the same representation. Hand-written code usually names wrapper types instead, because index-based access is easy to mix up.

Takeaway: A variant may repeat a type, but repeated types must be accessed by index.

Try it: g++ -std=c++17 main.cpp -o demo && ./demo

Open in Compiler Explorer ↗ Open SHOW_BUG variant ↗ Quiz this entry