如何声明模板模板参数

P45*_*ent 7 c++ templates c++11

假设我有两个类Foo1<T>和Foo2<T>.

然后我想创建一个bar引用a std::vector<Foo1<T>>或a的函数std::vector<Foo2<T>>但总是返回一个std::vector<Foo1<T>>:

template<class T, class Y> std::vector<Foo1<T>> bar(std::vector<Y<T>>&)

可悲的是,编译器不喜欢这个<Y<T>>位.这方面的一个方法是提供两个重载但是有一种方法我可以安排上面所以这是正确的吗?

son*_*yao 17

您需要模板模板参数:

template<class T, template <typename> class Y> 
std::vector<Foo1<T>> bar(std::vector<Y<T>>&) {}
Run Code Online (Sandbox Code Playgroud)

  • 从C++ 14开始,``Y`也可以用`typename`声明,而不是只用`class`声明.因此,总是可以声明`T`参数.只是在语言中添加了一点语法一致性. (2认同)