1

以下点头测试代码:

#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”模板的原因,还是编译器错误?

如果我删除模板,我会得到相同的结果,正如您对内联函数所期望的那样。

(相关问题)

4

2 回答 2

3

对于第一个错误尝试

#include <typeinfo>

不是

#include <typeinfo.h>
于 2009-12-02T12:23:21.103 回答
2

似乎我只回答了问题的第二部分,所以这里我也回答第一部分:

这就是 boost any 中没有包含“is_any”模板的原因吗?

没有实际需要is_any,改为执行以下操作:

if (const std::string* s = boost::any_cast<std::string>(&a))
{
   std::cout << "string = " << *s << '\n';
}
else if (const double* d = boost::any_cast<double>(&a))
{
   std::cout << "double = " << *d << '\n';
}

但这不是可扩展的,而是更喜欢使用boost::variant

它是编译器错误吗?

这是 Sun CC 中的一个编译器错误。gcc 是正确的,类型"Can you really..."char[18],不满足 boost::any 的要求:

  • ValueType 是 CopyConstructible 的。
  • ValueType 是可选的 Assignable。所有形式的分配都需要强大的异常安全保证。
  • ValueType 的析构函数支持不抛出异常安全保证。
于 2009-12-02T12:18:04.247 回答