boost::variant

#define _SCL_SECURE_NO_WARNINGS
#include <iostream> 
using namespace std;
#include <boost/variant.hpp>
#include <boost/variant/apply_visitor.hpp>//apply_visitor
#include <boost/variant/detail/apply_visitor_delayed.hpp>//apply_visitor_delayed_t
#include <algorithm>
#include <vector>
using namespace boost;
struct var_print : public static_visitor<>
{
	template<typename T>
	void operator()(T &i) const// 普通类型
	{
		cout << i << endl;
	}
	template<typename T>
	void operator()(vector<T>& v)
	{
		for (auto it : v)
		{
			cout << it << endl;
		}
	}
};

int main(int argc, char *argv[])
{

	boost::variant <int, std::string, double, char> u;// 可单次存放<>中的某一类型
	u = 4;
	assert(u.type() == typeid(int));
	int i = boost::get<int >(u);
	std::cout << "int : " << i << std::endl;// int : 4
	boost::get<int >(u) *= 10;
	std::cout << boost::get<int >(u) << std::endl;// 40

	u = "hello world!";
	std::string s = boost::get <std::string>(u);
	std::cout << "string : " << s << std::endl;// string : hello world!
	cout << u.which() << endl;// 1 当前类型的位置 

	u = 1.2;
	double d = boost::get<double >(u);
	std::cout << "double : " << d << std::endl;// double : 1.2

	u = 'c';
	char e = boost::get<char >(u);
	std::cout << "char : " << e << std::endl;// char : c

	//u = 1.4;
	//float f = boost::get<float >(u);// 错误,没有float存储类型
	//std::cout << "float : " << f << std::endl;


	// 访问者模式
	var_print vp;
	// 应用访问器需要函数apply_visitor
	apply_visitor(vp, u);// c
	// 以下两行和apply_visitor(vp, u);效果一样
	apply_visitor_delayed_t<var_print> avdt = apply_visitor(vp);
	avdt(u);// c

	// 针对vector重载operator()访问器
	boost::variant <std::string, vector<int>> v;
	v = vector<int>({ 1, 2, 3, 4 });
	apply_visitor(vp, v);// 1, 2, 3, 4 

	// 对容器内所有的variant元素进行访问器操作
	vector<boost::variant <std::string, vector<int>>> vec;
	vec.push_back((v));
	for_each(vec.begin(), vec.end(), apply_visitor(vp));// 1, 2, 3, 4
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值