-1

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.

10
  • Why was I downvoted? Commented Oct 31, 2016 at 0:45
  • What are you trying to do here? You're talking a lot about possible solutions, but not about your problem. Commented Oct 31, 2016 at 1:07
  • I am trying to specify the implementation of map for Database. I want to be able to write Database<std::map> or Database<custom_map> and have the map elements of Database be implemented in the specified way. Commented Oct 31, 2016 at 1:12
  • I'm not sure you're tackling this problem the right way. Templates are trouble. Why not have a base class of some kind with a well-defined interface, then store that as a pointer so you can pass in an arbitrary subclass. Commented Oct 31, 2016 at 1:24
  • I considered that. However, stackoverflow.com/questions/20829860/… seemed to indicate that templates were a more idiomatic solution. Commented Oct 31, 2016 at 1:28

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.