Any Type in C++

Level 5527 keystrokes

std::any can hold a single value of any type. The loop checks the stored type with type() == typeid(...) and reads the value with any_cast. The names printed by type().name() depend on the compiler (the output shows clang/libc++).

C++ code

// Each element can hold a value of a different type
1vector<any> items;
// Stores an int, a double, a string and a vector<int>
2items.push_back(42);
3items.push_back(3.14);
4items.push_back(string("hello"));
5items.push_back(vector<int>{1, 2, 3});
6
7for (const auto& item : items) {
// type().name() is implementation-defined: "i" and "d" here, mangled names for classes
8 cout << "Type: " << item.type().name() << " -> ";
// Compares the stored type with a typeid
9 if (item.type() == typeid(int))
// any_cast reads the value; a wrong type would throw bad_any_cast
10 cout << any_cast<int>(item);
11 else if (item.type() == typeid(double))
12 cout << any_cast<double>(item);
13 else if (item.type() == typeid(string))
14 cout << any_cast<string>(item);
// The vector<int> matches none of the checks
15 else
16 cout << "[complex type]";
17 cout << endl;
18}
19
// has_value() is true for 42: prints "Has value: 1"
20cout << "Has value: " << items[0].has_value() << endl;

Output

Type: i -> 42
Type: d -> 3.14
Type: NSt3__112basic_stringIcNS_11char_traitsIcEENS_9allocatorIcEEEE -> hello
Type: NSt3__16vectorIiNS_9allocatorIiEEEE -> [complex type]
Has value: 1
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.

  • <× 27
  • (× 21
  • )× 21
  • ;× 12
  • .× 11
  • "× 10
  • _× 8
  • =× 6
  • >× 6
  • :× 3

More C++ examples at level 5

← C++ typing practice