把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当前的类型进行检查,
-
相关阅读:
C++day3
Opencv中的直方图均衡
07 索引
与君共勉:致毕业生
cpp学习笔记:STL queue容器
Tomcat最大并发数及在线用户数
高防IP与CDN该如何选择
Redis持久化策略原理及使用场景选择
LeetCode HOT 100 —— 49.全排列
一文就懂大语言模型Llama2 7B+中文alpace模型本地部署
-
原文地址:https://blog.csdn.net/jiemashizhen/article/details/128070142