把variant类型作为参数传递给一个函数,并不像想象的那么简单:
#include <iostream>
#include <variant>
#include <string>
using namespace std;
void pOut(variant<int, double, string>& v)
{
if(auto p = get_if<int>(&v))
{
cout<<"v is int, and value is "<<*p<<endl;
}
else if(auto p = get_if<double>(&v))
{
cout<<"v is double, and value is "<<*p<<endl;
}
else if(auto p = get_if<string>(&v))
{
cout<<"v is string, and value is "<<*p<<endl;
}
}
int main()
{
variant<int, double, string> v1{8}, v2{3.14}, v3{"hi"};
pOut(v1);
pOut(v2);
pOut(v3);
return 0;
}
运行程序输出:
v is int, and value is 8
v is double, and value is 3.14
v is string, and value is hi
可以看到需要在函数里对variant当前的类型进行检查,