c++ - boost 任何使用

标签 c++ boost map insert boost-any

如何将我自己的类对象从 boost 插入到 ptr_map 中。这些对象是模板化的,所以我不能在 map 中使用一些静态类型名称。所以我做了:

ptr_map<string, any> someMap;

我的类继承了boost::noncopyable

someMap.insert("Test", new MyClass<SomeTemplate>());

错误是:错误:没有匹配函数来调用‘boost::ptr_map


更新: 我宁愿制作一些包装器并且不使用 boost::any。所以:

class IWrapper { };
class MyClass : public IWrapper { };

ptr_map<string, IWrapper> someMap;
someMap.insert("Test", new MyClass<SomeTemplate>());

为什么它不起作用(同样的错误)?我可以将继承的类传递给父接口(interface)。怎么了?

最佳答案

到目前为止,大多数此类问题都应该使用公共(public)基类来解决。当所有的类都将被类似地使用时就是这种情况。运行时多态性。

我看到了不允许使用公共(public)基类的正当理由。在这种情况下,boost::variant 通常会提供更好的服务,因为仍然有一些方法可以统一对待每个项目(访问者)。编译时多态性。

我从未见过 for boost::any 的合法用途。我并不是说没有,但它非常罕见,我从未遇到过。


也就是说,试试这个。

std::map<std::string,boost::any> someMap;
boost::any insanity = new MyClass<SomeTemplate>;
someMap.insert("Test",insanity);

boost::ptr_map<std::string,boost::any> someMap;
boost::any* ive_lost_it = new boost::any( new MyClass<SomeTemplate> );
someMap.insert("Test", ive_lost_it );

关于c++ - boost 任何使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3062739/

相关文章:

c++ - 为什么 QCheckBox 的信号没有发出?

C++:静态成员函数和变量——静态变量的重新定义?

c++ - 构建的 ffmpeg.exe 没有按预期工作

c++ - 在没有 print_graph() 的情况下使用 boost filtered_graph

c++ - 如何每 200 秒使 io_service 发布特定功能?

ios - CATiledLayer subview 导致内存警告和崩溃

python - 使用 Python 减少对列表

c++ - 将二叉树保存到文件

c++ - boost::intrusive_ptr 改变指针地址

C++ STL map::erase a non-existing key