Andrei Bârsan
Andrei Bârsan

Reputation: 3523

C++ hash_map with un-specialized templates as values

I would like to have a std::hash_map that maps (for instance) regular std:strings to multiple different specializations of another template class.

This example is what I'm trying to achieve (it's wrong and doesn't compile, though):

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);
}

Upvotes: 4

Views: 281

Answers (2)

Mike Seymour
Mike Seymour

Reputation: 254431

The map can only store a single value type, so it can't directly store objects of different types; and different specialisations of a class template are different types.

Common solutions are:

  • Store pointers to a polymorphic base type, and access the real type via virtual functions or RTTI. You will need to be a bit careful about managing the objects themselves - either store smart pointers, or keep them in some other data structure(s).
  • Store a discriminated union type such as boost::variant or boost::any

Upvotes: 9

tadman
tadman

Reputation: 211560

You generally can't have an element in your hash that's of an incomplete type. Can you make a non-template base class that the others can inherit from?

The reason for this largely boils down to how the compiler will interpret your request. If it can't compute the size of your Foo structure, it can't create the internals for the hash_map.

Upvotes: 2

Related Questions