June 2018
Intermediate to advanced
348 pages
8h 45m
English
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 = ...Read now
Unlock full access