I want to keep some kind of container where a type maps to one value of the type. So essentially what I want is a std::map<std::typeindex, T>
where T depends on the type I index it with. std::map
doesn't look like a nice way of doing this because the types are rigid. What is the simplest solution I can use for doing this?
If you map to a type-erased container like boost::any
, you can at least recover the type if you know what it is:
std::map<std::typeindex, boost::any> m;
m[typeid(Foo)] = Foo(1, true, 'x');
Foo & x = boost::any_cast<Foo&>(m[typeid(Foo)]);
You could use a 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>
Or course you would add some wrapper to ensure that the two T
s per line match and you don't accidentially access an empty shared_ptr<void>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With