代碼如下:
#include <boost/any.hpp>
using boost::any;
#include <iostream>
#include <list>
#include <string>
using namespace std;
typedef list<boost::any > any_list;
int main()
{
any_list al;
//先填充幾個值
al.push_back(11); // 加了一個整形
al.push_back(123.456); // 加了一個浮點型
// 加一個字符串,al.push_back("abcdefg");錯誤,因爲會被當錯字符串處理
al.push_back(string("abcdefg"));
// 訪問這幾個值
any_list::iterator it;
boost::any anyone;
for (it = al.begin(); it != al.end(); it ++)
{
anyone = *it;
if (anyone.type() == typeid(int))
{
cout<<boost::any_cast<int>(*it) << endl;
}
else if (anyone.type() == typeid(double))
{
cout<<boost::any_cast<double>(*it) << endl;
}
else if (anyone.type() == typeid(string))
{
cout<<boost::any_cast<string>(*it) << endl;
}
}
return 0;
}
運行結果如下: