c++ - How can I switch between std::map or std::unordered_map as a container in a class? -
i have ifdef typedef in class:
#ifdef hashmap typedef std::unordered_map<unsigned int, l1entry> l1; //c++ 11 #else typedef std::map<unsigned int, l1entry> l1; #endif
i need control container used when create new object of class. best approach this?
make container template parameter of class:
template<typename maptype> class myclass { public: // ... private: maptype mymap; };
and instantiate so:
myclass< std::map<unsigned int, l1entry> > obj; myclass< std::unordered_map<unsigned int, l1entry> > obj2;
there's container in standard library this, take @ std::queue default implemented std::deque
can specify container, long container provides operations.
here's version have 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 final version, show how can split code in .h/.cpp (everything goes in .h except section 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 #include <whatever.h>) template<template <typename...args> class container> void myclass< container >::printmap() { // ... actual printing std::cout << "you'd print stuff here." << std::endl; } // end of cpp chunk #endif // mymap_h
and main.cpp:
#include "mymap.h" int main() { myclass<std::map> obj; myclass<std::unordered_map> obj2; obj.printmap(); obj2.printmap(); return 0; }
Comments
Post a Comment