boost::variant的简单介绍

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: 356
The type is double, the value is: 3.14
The type is string, the value is: hello world
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值