首页 > 学院 > 开发设计 > 正文

boost::variant的简单介绍

2019-11-06 08:11:36
字体:
来源:转载
供稿:网友

boost::variant简介 boost::Variant 是定义在boost/variant.hpp中的模板类,它的功能类似与union。Variant是一个模板,所以在使用时必须传入至少一个类型参数。Variant实例所存储的数据类型只能是传入类型中的一种。 例如:

boost::Variant<double, int, string> variant;variant = "hello world!";variant = 3.14;variant = 356;

boost::apply_visitor()与boost::static_visitor

boost::apply_visitor()是boost中提供的函数,该函数的第一个参数必须是boost::static_visitor类型的子类,第二个参数是boost::Variant类型。boost::static_visitor的子类中必须提供Operator()()的重载,分别用于处理boost::Variant中传入的不同类型的参数。在使用时boost::apply_visitor会自动根据第二个参数类型来调用operator()()。 例如: 源码实例:

#include <iostream>#include <boost/variant.hpp>#include <string>using namespace std;struct Var: public boost::static_visitor<>{ void operator()(const double &t) { cout << "The type is double, the value is: " << t << endl; } void operator()(const int &t) { cout << "The type is int, the value is: " << t << endl; } void operator()(const string &t) { cout << "The type is string, the value is: " << t << endl; }};int main(int argc, char* argv[]){ Var v; boost::variant<double, int, string> var; var = 356; boost::apply_visitor(v, var); var = 3.14; boost::apply_visitor(v, var); var = "hello world"; boost::apply_visitor(v, var); return 0;}

运行结果:

The type is int, the value is: 356The type is double, the value is: 3.14The type is string, the value is: hello world
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表