Specialization Template

Is there a way to get a template from a template specialization? For instance. std::unordered_map from a variable of type std::unordered_map<char, char> , which will be passed as a template template parameter.

Minimal example:

 #include <unordered_map> template <template <class ...> class t_map> class A { public: typedef t_map <int, int> map_type; }; int main(int argc, char const **argv) { std::unordered_map<char, char> map; // decltype yields std::unordered_map<char, char> (as expected). typename A<decltype(map)>::map_type map_2; return 0; } 
+5
source share
2 answers

Here is an example of how to create a new type where the template parameter (int) is exchanged (line by line):

 #include <vector> #include <string> template <typename container, typename newt> struct replace; template <typename p1, typename alloc, template<typename,typename > class containerTemplate, typename newt> struct replace<containerTemplate<p1,alloc>,newt> { public: typedef containerTemplate<newt,alloc> result; }; int main() { replace<std::vector<int>,std::string>::result vs; vs.push_back("a string"); } 

This way you can pass std :: unordered_map as a template parameter to your function and replace char with any other type you want. You may need to customize your example to your needs. But the principle must be clear.

EDIT: More general for containers, less general for replacement:

 template <class Container> struct replace; template <template <class...> class Container, class... Ts> struct replace<Container<Ts...>> { typedef Container<std::string> result; }; 
+3
source

I'm not quite sure this is what you are looking for, but would a template alias declaration match your example?

 #include <iostream> #include <map> template <typename T> using mm = std::map<T, T>; int main() { mm<int> i; mm<char> c; } 
0
source

Source: https://habr.com/ru/post/1242871/


All Articles