boost::variant的诡异现象引发的思考

#include <iostream>
#include <string>
#include <boost/optional.hpp>
#include <boost/variant.hpp>
#include <boost/any.hpp>
#include <list>
using namespace std;
using namespace boost;
struct MyPair
{
	template<typename T1,typename T2>
	MyPair(const T1&& k, const T2&& v):key(k), value(v){}
	template<typename T1, typename T2>
	MyPair(const T1& k, const T2& v) : key(k), value(v) {}
#if 1 //bug fix
	template<typename T1> MyPair(const T1 &k, const char* v) : key(k), value(string(v)) {}
	template<typename T2> MyPair(const char* k, const T2& v) : key(string(k)), value(v) {}
	MyPair(const char* k, const char* v) : key(string(k)), value(string(v)) {}
#endif
	boost::variant<int, long, double, bool, string> key;
	boost::variant<int, long, double, bool, string> value;
};
class test
{
	class my_visitor : public boost::static_visitor<>
	{
	public:
		template<typename T1, typename T2>
		void operator()(const T1 &key, const T2 &value) const
		{
			//cout << typeid(T1).name()<<":"<< typeid(T2).name() << endl;
			cout << boost::get<T1>(key) << ":" << boost::get<T2>(value) << endl;
		}	
	};
public:
	test(const std::initializer_list<MyPair >& pairs)
		:test(begin(pairs),end(pairs))
	{
	}
	template <typename T>
	test(const T& b,const T &d)
	{
		for_each(b, d, [](auto &t) {boost::apply_visitor(my_visitor(), t.key, t.value); });
	}
};
int main()
{
	test t({ {"kl", "111"},{"k2", 123},{"k3",456} });
	return 0;
}


上代码,输出

kl:111
k2:123
k3:456

把fix出开关关闭 输出

1:1
1:123
1:456

猜猜为什么呢?

原来编译器优先把const char*转换为bool,而不是string,参考链接

https://stackoverflow.com/questions/13268608/boostvariant-why-is-const-char-converted-to-bool


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值