我想保留某种类型的容器,其中类型映射到该类型的一个值。基本上我想要的是std::map<std::typeindex, T>
,其中T取决于我用它索引的类型。 std::map
看起来不是一种很好的方式,因为类型是僵化的。我可以用来做这个的最简单的解决方案是什么?
答案 0 :(得分:4)
如果映射到类型删除的容器(如boost::any
),如果您知道它是什么,则至少可以恢复该类型:
std::map<std::typeindex, boost::any> m;
m[typeid(Foo)] = Foo(1, true, 'x');
Foo & x = boost::any_cast<Foo&>(m[typeid(Foo)]);
答案 1 :(得分:2)
您可以使用shared_ptr<void>
:
std::map<std::typeindex, std::shared_ptr<void>> m;
m[typeid(T)] = std::make_shared<T>(...);
auto pT = std::static_pointer_cast<T>(m[typeid(T)]); // pT is std::shared_ptr<T>
当然,您可以添加一些包装,以确保每行匹配两个T
,并且您不会意外地访问空shared_ptr<void>
。