#include <iostream>
#include <boost/any.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/assign/list_of.hpp>
using namespace std;
using namespace boost;
// 类型检测
template<typename T>
bool can_cast(any &a)
{
return typeid(T) == a.type();
}
// 得到引用
template<typename T>
T& get(any &a)
{
BOOST_ASSERT(can_cast<T>(a));
return *any_cast<T>(&a);
}
// 得到指针
template<typename T>
T* get_pointer(any &a)
{
BOOST_ASSERT(can_cast<T>(a));
return any_cast<T>(&a);
}
// 智能指针any
template<typename T>
any make_ptr_any(T *p = NULL)
{
return any(boost::shared_ptr<T>(p));
}
// 专门为shared_ptr指针类型写一个引用函数
template<typename T>
boost::shared_ptr<T>& get_shared_ptr(any &a)
{
BOOST_ASSERT(can_cast<boost::shared_ptr<T>>(a));
return *any_cast<boost::shared_ptr<T>>(&a);
}
int main()
{
any a = 10;
a = string("aaa");
cout << any_cast<string>(a);
//cout << any_cast<int>(a);// 类型错误
decltype(a) b = 1.231;
// 最好不要赋值为内置指针(安全起见使用智能指针)
int *p = new int(10);
a = p;
delete(p);
if (!a.empty() && any_cast<int*>(a))
cout << *any_cast<int*>(a) << endl;// 这里输出的值是不确定的
cout << a.type().name() << endl;// int*
a = make_ptr_any<string>(new string("bbb"));
cout << *any_cast<boost::shared_ptr<string>>(a) << endl;// bbb
cout << *get_shared_ptr<string>(a) << endl;// bbb
assert(can_cast<double>(b));
cout << get<double>(b) << endl;//1.231
get<double>(b) = 10;
cout << get<double>(b) << endl;//10
*get_pointer<double>(b) = 20;
cout << get<double>(b) << endl;//20
// 存放不同的类型
std::vector<any> vec = (assign::list_of<any>(1),2.1,string("vbvv"));
//vec.push_back(1);
//vec.push_back(2.1);
//vec.push_back(string("vbvv"));
for (any it : vec)
{
if (can_cast<int>(it))
{
cout << "int:" << get<int>(it) << endl;// 1
}
else if (can_cast<double>(it))
{
cout << "double:" << get<double>(it) << endl;// 2.1
}
else if (can_cast<string>(it))
{
cout << "string:" << get<string>(it) << endl;// vbvv
}
}
return 0;
}