Search code examples
c++templatesstltemplate-templates

template template parameter for stl containers behaving different from custom template class


I have the following struct and function

template <class T> struct C {};

template <template <class S> class T, class U> void f() { T<U> tu; }

when templating f() with C I do not get an error, when templating it with say std::vector I do.

int main() {
  f<C, int>();
}

yields no errors

int main() {
    f<std::vector, int>();
}

yields

error: no matching function for call to 'f'
f<std::vector, int>();
^~~~~~~~~~~~~~~~~~~~~~~~
note: candidate template ignored: invalid explicitly-specified argument for template parameter 'T'
template <template <class S> class T, class U> void f() { T<U> tu; }

What is the difference between C and std::vector here?


Solution

  • That's because vector has two template parameters, not one (T and Allocator).

    You can either change your f template to accept two template parameters (or a variadic pack):

    template <template <class...> class T, class U> void f() { T<U> tu; }
    

    or you can alias vector to a 1-parameter template:

    template<typename T>
    using vec = std::vector<T>;