Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Template from template specialization

Tags:

c++

templates

Is there a way to get the template from a template specialization? E.g. std::unordered_map from a variable of type std::unordered_map<char, char> to 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;
}
like image 983
tsnorri Avatar asked Sep 25 '22 09:09

tsnorri


1 Answers

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

#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 template parameter to your function and replace char by any other type you want. You may need to adjust my example to your needs. But the principle should be clear.

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

template <class Container>
struct replace;

template <template <class...>  class Container, class... Ts>
struct replace<Container<Ts...>> {
   typedef Container<std::string> result;
};
like image 166
MarkusParker Avatar answered Sep 29 '22 16:09

MarkusParker