MCPcopy Create free account
hub / github.com/0voice/cpp_new_features / main

Function main

cpp_17/006_variant_variant.cpp:6–37  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

4#include <iostream>
5
6int main()
7{
8 std::variant<int, float> v, w;
9 v = 42; // v contains int
10 int i = std::get<int>(v);
11 assert(42 == i); // succeeds
12 w = std::get<int>(v);
13 w = std::get<0>(v); // same effect as the previous line
14 w = v; // same effect as the previous line
15
16// std::get<double>(v); // error: no double in [int, float]
17// std::get<3>(v); // error: valid index values are 0 and 1
18
19 try {
20 std::get<float>(w); // w contains int, not float: will throw
21 }
22 catch (const std::bad_variant_access& ex) {
23 std::cout << ex.what() << '\n';
24 }
25
26 using namespace std::literals;
27
28 std::variant<std::string> x("abc");
29 // converting constructors work when unambiguous
30 x = "def"; // converting assignment also works when unambiguous
31
32 std::variant<std::string, void const*> y("abc");
33 // casts to void const * when passed a char const *
34 assert(std::holds_alternative<void const*>(y)); // succeeds
35 y = "xyz"s;
36 assert(std::holds_alternative<std::string>(y)); // succeeds
37}

Callers

nothing calls this directly

Calls

no outgoing calls

Tested by

no test coverage detected