Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Registry of different types of data

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?

like image 461
user2852456 Avatar asked Oct 06 '13 19:10

user2852456


2 Answers

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)]);
like image 67
Kerrek SB Avatar answered Nov 10 '22 07:11

Kerrek SB


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 Ts per line match and you don't accidentially access an empty shared_ptr<void>.

like image 34
Daniel Frey Avatar answered Nov 10 '22 08:11

Daniel Frey