std::variant代替union

std::variant<int, double, std::wstring> var1{ 1.0 };
std::variant<int, double, std::wstring> var2{ L"2" };
std::variant<int, std::wstring> var3{ 3 };

//assign
var2 = L"abc";
var1 = L"str1";
var2.emplace<int>(1);
std::wcout << L"the var1 = " << std::get<std::wstring>(var1) << std::endl; 
std::wcout << L"the var2 = " << std::get<0>(var2) << std::endl;
std::get可以在模板参数里面传入类型 或者int值,0代表第一个模板类型,1代表第二个模板类型
//swap
std::swap(var1, var2);//可以直接用swap交换值

//determine the type of variant
if (var2.index() == 2) {
//it's wstring type
std::wcout << L"var2 is wstring type" << std::endl;
}
var1 = 100;
if (std::holds_alternative<int>(var1)) {
std::wcout << L"var1 is " << typeid(int).name() << std::endl;
}

//get type by index of variant 
std::variant_alternative<2, decltype(var1)>::type val{ L"123" };

// get value
var1 = 1;
std::wcout << L"var1 = " << std::get<int>(var1) << std::endl;

var2 = L"2";
std::wcout << L"var2 = " << std::get<2>(var2) << std::endl;
//std::get_if 判断是不是指定类型,然后决定要不要继续执行下去,注意传入的类型必须要是在模板中包含的类型,否则会报错
if (auto pV = std::get_if<int>(&var3)){
std::wcout << L"var3 = " << *pV << std::endl;
}

你可能感兴趣的:(C++奇淫技巧,union,variant)