C ++ hash_map with non-specialized templates as values

I would like to have std::hash_map , which maps (for example) regular std:string to several different specializations of another template class.

This example is what I'm trying to achieve (this is incorrect and does not compile):

 template<typename T> class Foo { public: Foo(T _value) { this-> value = _value; } private: T value; }; int main() { hash_map<string, Foo> various_foos; various_foos["foo"] = Foo<int>(17); various_foos["bar"] = Foo<double>(17.4); } 
+4
source share
2 answers

Typically, you cannot have an element in your hash of an incomplete type. Can you create a base class without templates that others can inherit?

The reason for this pretty much comes down to how the compiler will interpret your request. If it cannot calculate the size of your Foo structure, it will not be able to create internals for hash_map .

+2
source

A map can only store one type of value; therefore, it cannot directly store objects of different types; and the various specializations of the class template are different types.

General solutions:

  • Save pointers to the polymorphic base type and access the real type using virtual functions or RTTI. You need to be a little careful in managing the objects themselves - either store smart pointers, or store them in some other data structure.
  • Save the discriminated type of union, for example boost::variant or boost::any
+9
source

All Articles