#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