7

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

ptr_map<string, any> someMap;

我的班级继承了boost::noncopyable

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

错误是:错误:no matching function for call to ‘boost::ptr_map


UPD:我更喜欢做一些包装,不要使用 boost::any。所以:

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

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

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

4

2 回答 2

3

到目前为止,大多数时候这种类型的问题应该用一个通用的基类来解决。这是所有类都将被类似使用的情况。运行时多态性。

我已经看到了不允许公共基类的正当理由。在这种情况下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 );
于 2010-06-17T14:57:43.297 回答
1

First you must provide any* to your ptr_map.
Then the key must be an lvalue (due to exception-safety issues).

boost::ptr_map<std::string, any> someMap;
any * p = new any(MyClass<Sometype>);
std::string test = "test";
someMap.insert(test, p);

-- edit
Same thing if you are using a wrapper class. the key must be an lvalue.

By the way the problem with the wrapper/base class here is that you won't be able to get back to the original type (and you don't have dynamic polymorphism either because of template type).

于 2010-06-17T15:30:20.563 回答