把variant类型作为参数传递给一个函数,并不像想象的那么简单:
- #include
- #include
- #include
- 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<
- }
- else if(auto p = get_if<double>(&v))
- {
- cout<<"v is double, and value is "<<*p<
- }
- else if(auto p = get_if
(&v)) - {
- cout<<"v is string, and value is "<<*p<
- }
- }
-
- 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当前的类型进行检查,
-
相关阅读:
系统报错“由于找不到msvcp140.dll无法继续执行代码”的处理方法
[附源码]Python计算机毕业设计Django高校流浪动物领养网站
zookeeper教程
if条件表达式和while循环语句
pandas 排序方法: sort_index(),sort_values()
技术分享 | 如何编写同时兼容 Vue2 和 Vue3 的代码?
NeurIPS 2022 | 涨点神器!利用图像辅助三维点云分析的训练新范式
vscode远程连接XHR(wget download failed)解决方法
X Spring File Storage实现文件上传与下载
技术干货|昇思MindSpore Lite1.5 特性发布,带来全新端侧AI体验
-
原文地址:https://blog.csdn.net/jiemashizhen/article/details/128070142