C++ Reactive Programming
上QQ阅读APP看书,第一时间看更新

Variant type

A geeky definition of variant would be "type safe union". We can give a list of types as a template argument while defining variants. At any given time, the object will hold only one type of data out of the template argument list. std::bad_variant_access will be thrown if we try to access an index that does not hold the current value. The following code does not handle this exception:

//------------ Variant.cpp
//------------- g++ -std=c++1z Variant.cpp
#include <variant>
#include <string>
#include <cassert>
#include <iostream>
using namespace std;

int main(){
std::variant<int, float,string> v, w;
v = 12.0f; // v contains now contains float
cout << std::get<1>(v) << endl;
w = 20; // assign to int
cout << std::get<0>(w) << endl;
w = "hello"s; //assign to string
cout << std::get<2>(w) << endl;
}