以下点头测试代码:
#include <iostream>
#include <list>
#include <boost/any.hpp>
#include <boost/foreach.hpp>
#include <typeinfo.h>
using boost::any_cast;
using std::cout;
using std::cerr;
typedef std::list<boost::any> many;
template <typename T>
inline bool is_any(const boost::any& op)
{
return (op.type() == typeid(T));
}
int main()
{
many theStrangeList;
theStrangeList.push_back("Can you really...");
theStrangeList.push_back(std::string ("do random types in 1 container?"));
theStrangeList.push_back(6.359);
theStrangeList.push_back(7);
BOOST_FOREACH(boost::any a, theStrangeList)
{
try
{
if (is_any<const char*>(a))
{
cout << any_cast<const char*>(a) << '\n';
}
else if (is_any<std::string>(a))
{
cout << any_cast<std::string>(a) << '\n';
}
else if (is_any<double>(a))
{
cout << "double = " << any_cast<double>(a) << '\n';
}
}
catch (const boost::bad_any_cast& e)
{
cerr << e.what();
cerr << "\n";
}
}
return 0;
}
使用 Sun 的 CC 编译器和默认设置编译和工作正常。但是,当使用 g++ 时,我得到以下信息:
$ g++ -I$BOOST_ROOT -o myany myany.cpp
myany.cpp:5:22: typeinfo.h: No such file or directory
/ilx/boost_1_41_0/boost/any.hpp: In constructor `boost::any::holder<ValueType>::holder(const ValueType&) [with ValueType = char[18]]':
/ilx/boost_1_41_0/boost/any.hpp:47: instantiated from `boost::any::any(const ValueType&) [with ValueType = char[18]]'
myany.cpp:21: instantiated from here
/ilx/boost_1_41_0/boost/any.hpp:122: error: ISO C++ forbids assignment of arrays
这是g++ 3.4.3版本,所以在4.x版本上可能会有所不同,我稍后会尝试。这是 boost any 中没有包含“is_any”模板的原因,还是编译器错误?
如果我删除模板,我会得到相同的结果,正如您对内联函数所期望的那样。