Search code examples
c++templatestemplate-meta-programming

Extract container template for storing a different type


Given a container of a certain type as input, is it possible to "extract" the container template and instantiate it for a different type? For example:

void f ( auto& x ) {
  getContainerTemplate(x)<int> a (10); // getContainerTemplate() 
  // is some magic function.
}

The effect of f() should be the following depending on the type of x:

void f ( std::vector<double>& x ) {
  std::vector<int> a(10);
}

or

void f ( parlay::sequence<double>& x ) { // parlay::sequence is
  // another container template storing elements contiguously.
  parlay::sequence<int> a(10);
}

Solution

  • Yes, it is possible. Using a "template template parameter" (see What are some uses of template template parameters?) instead of auto will allow f() to deduce a template type, which you can then instantiate with your own parameters, eg:

    template< template<typename, typename...> class Container, typename T >
    void f ( Container<T>& x ) {
      Container<int> a(10);
      ...
    }
    

    Online Demo