Make the container a template parameter of the class:
template<typename MapType>
class MyClass
{
public:
// ...
private:
MapType myMap;
};
And you would instantiate like so:
MyClass< std::map<unsigned int, L1Entry> > obj;
MyClass< std::unordered_map<unsigned int, L1Entry> > obj2;
There's a container in the standard library that does exactly this, take a look at std::queue by default it is implemented with an std::deque
but you can specify another container, so long as this container provides certain operations.
Here's another version where you only have to specify std::map
or std::unordered_map
:
#include <map>
#include <unordered_map>
typedef size_t L1Entry;
template<template <typename...> class Container>
class MyClass
{
typedef Container<int, L1Entry> MapType;
public:
// ...
private:
MapType myMap;
};
int main()
{
MyClass<std::map> obj;
MyClass<std::unordered_map> obj2;
}
OK! Here's a final version, to show you how you can split the code in .h/.cpp (everything goes in .h except for the section I marked):
#ifndef MYMAP_H
#define MYMAP_H
#include <map>
#include <unordered_map>
#include <iostream>
typedef size_t L1Entry;
template<template <typename...> class Container>
class MyClass
{
typedef Container<int, L1Entry> MapType;
public:
void printMap();
private:
MapType myMap;
};
// START OF CPP CHUNK (replace with #include <whatever.h>)
template<template <typename...Args> class Container>
void MyClass< Container >::printMap()
{
// ... do the actual printing
std::cout << "You'd print stuff here." << std::endl;
}
// END OF CPP CHUNK
#endif // MYMAP_H
And this would be the main.cpp:
#include "mymap.h"
int main()
{
MyClass<std::map> obj;
MyClass<std::unordered_map> obj2;
obj.printMap();
obj2.printMap();
return 0;
}