Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
}
like image 281
Andrei Bârsan Avatar asked Dec 20 '22 09:12

Andrei Bârsan


1 Answers

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
like image 187
Mike Seymour Avatar answered Dec 24 '22 02:12

Mike Seymour