Halbort Halbort - 1 month ago 9
C++ Question

Passing Map Implementation through Templates

I have a class that stores two maps like so:

class Database {
std::map<A,B> map1;
std::map<C,A> map2;
};


I have just included part of the class.
Database
has more functions and data elements that I have not included.

I want to change the implementation of map from
std::map
to something else that has the same public interface. This seems to be a good place for templating.

Normally, I would write
template<class Map>
at the top and be done. However, there are a problem.

Map is not specialized within this class. For example, if I just need a Map. Writing template would be fine. I would define 'Database' as
Database<std::map<A, B>>
. However, I need two separate map instances.

Do I need to write
template<class Map1, class Map2>
and define 'Database' as
Database<std::map<A, B>>
? Or is there a better way of doing the templated definition. Or are templates the wrong technique for this situation?

Ideally, I would like to be able to write
Database<std::map>
. Is this possible?

I had previously checked:

Error when pass std::map as template template argument

Error passing map to template function in C++

Passing unspecialized template as a template parameter

However, these two not really deal with my problem of having two different parameterizations.

EDIT:
Overall, I am trying to specify the implementation of map for Database. I want to be able to write Database or Database and have the map elements of Database be implemented in the specified way.

Answer

You may be looking for template template parameters. Something like this:

template <template <class...> class Map>
class Database {
    Map<A, B> map1;
    Map<C, A> map2;
};

Database<std::map> dbOnStdMap;

Demo

Comments