Variant Type in C++

Level 5431 keystrokes

A variant holds one of several types at a time. visit calls a generic lambda with the value it currently holds, and if constexpr picks the branch for that type at compile time. index() returns the position of the active type (2 for string).

C++ code

// Value holds an int, a double or a string
1using Value = variant<int, double, string>;
2
// One value of each type; string("hello") makes the string alternative explicit
3Value values[] = {42, 3.14, string("hello")};
4
5for (const auto& v : values) {
// visit calls the lambda with the value currently stored in v
6 visit([](const auto& arg) {
// decay_t removes const and & to get the plain type
7 using T = decay_t<decltype(arg)>;
// if constexpr keeps only the matching branch when compiling
8 if constexpr (is_same_v<T, int>)
// Prints "int: 42"
9 cout << "int: " << arg << endl;
10 else if constexpr (is_same_v<T, double>)
// Prints "double: 3.14"
11 cout << "double: " << arg << endl;
12 else
// Prints "string: hello"
13 cout << "string: " << arg << endl;
14 }, v);
15}
16
// index() is the position of the active type: string is 2
17cout << "Index of last: " << values[2].index() << endl;

Output

int: 42
double: 3.14
string: hello
Index of last: 2
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • <× 28
  • "× 10
  • ;× 8
  • (× 8
  • )× 8
  • ,× 7
  • _× 5
  • :× 5
  • >× 4
  • [× 3

More C++ examples at level 5

← C++ typing practice