boost教程(十七):数据结构-variant

每一部分都单独注释的,运行时取消注释,将其他部分注释起来就可以。

/*
Boost.Variant 只能被视为固定数量的类型。
*/

#include <boost/variant.hpp> 
#include <boost/any.hpp> 
#include <vector>
#include <string> 
#include <iostream>


std::vector<boost::any> vector;

struct output :
	public boost::static_visitor<>
{
	void operator()(double &d) const
	{
		vector.push_back(d);
	}

	void operator()(char &c) const
	{
		vector.push_back(c);
	}

	void operator()(std::string &s) const
	{
		vector.push_back(s);
	}
};


//简化代码
struct output1 :
	public boost::static_visitor<>
{
	template <typename T>
	void operator()(T &t) const
	{
		vector.push_back(t);
	}
};


int main()
{

	/*
	给 v 指定了 double 类型和 char 类型。 注意, 一旦你将一个 int 值赋给了 v, 你的代码将不会编译通过。
	*/
	/*boost::variant<double, char> v;
	v = 3.14;
	v = 'A';*/





	/*
	上面的例子也可以用一个 union 类型来实现,
	 boost::variant 可以储存像 std::string 这样的 class 类型的数据。
	*/
	/*boost::variant<double, char, std::string> v;
	v = 3.14;
	v = 'A';
	v = "Hello, world!";
	*/





	
	/*
	//访问元素
	使用独立的 boost::get() 函数。
	和union一样,同时只能存在一个类型的数据, 在传入一种类型的数据后,在输出其他类型的数据会有异常
	boost::any 没有测试,
	*/
	/*boost::variant<double, char, std::string> v;
	v = 3.14;
	std::cout << boost::get<double>(v) << std::endl;
	v = 'A';
	std::cout << boost::get<char>(v) << std::endl;
	v = "Hello, world!";
	std::cout << boost::get<std::string>(v) << std::endl;*/
	



	/*
	所有 boost::variant 类型的值都可以被直接写入标准输入流这样的流中, 这可以在一定程度上让你避开运行时错误的风险。
	*/
	/*boost::variant<double, char, std::string> v;
	v = 3.14;
	std::cout << v << std::endl;
	v = 'A';
	std::cout << v << std::endl;
	v = "Hello, world!";
	std::cout << v << std::endl;
	*/





	/*
	Boost.Variant 提供了一个名为 boost::apply_visitor() 的函数。分别处理各种不同类型的数据,
	boost::apply_visitor() 
	第一个参数需要传入一个继承自 boost::static_visitor 类型的对象。
	这个类必须要重载 operator()() 运算符来处理 boost::variant 每个可能的类型。

	第二个参数是一个 boost::variant 类型的值。
	*/

	/*
	这种用法经典,一个vector中可以存储不同类型的数据
	*/
	/*boost::variant<double, char, std::string> v;
	v = 3.14;
	boost::apply_visitor(output(), v);
	v = 'A';
	boost::apply_visitor(output(), v);
	v = "Hello, world!";
	boost::apply_visitor(output(), v);*/




	/*
	如果对每种类型的操作都是一样的, 
	可以像下面的示例一样使用一个模板来简化你的代码。
	*/
	boost::variant<double, char, std::string> v;
	v = 3.14;
	boost::apply_visitor(output1(), v);
	v = 'A';
	boost::apply_visitor(output1(), v);
	v = "Hello, world!";
	boost::apply_visitor(output1(), v);


	const std::type_info &ti = vector[2].type();
	std::cout << ti.name() << std::endl;

	//元素的访问成了问题(迭代器,[]无法支持,其他方法还没试过)
	std::cout << boost::any_cast<std::string>(vector[2]) << std::endl;
	
	//以下是错误语句
	//std::cout << (double)(*vector.begin()) << std::endl;
	
	system("pause");
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值