stl 容器的模板模板参数与自定义模板的行为不同 class

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

我有以下结构和函数

template <class T> struct C {};

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

当用 C 模板化 f() 时我没有得到错误,当用 std::vector 模板化它时我有。

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

没有产生错误

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

产量

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; }

这里的Cstd::vector有什么区别?

那是因为 vector 有两个模板参数,而不是一个(TAllocator)。

您可以更改 f 模板以接受两个模板参数(或可变参数包):

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

或者您可以将 vector 别名为 1 参数模板:

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

区别在于vector有两个模板参数,不是一个。要解决此问题,您可以使用

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