C++中的模板模板参数

template template argument in C++

本文关键字:参数 C++      更新时间:2023-10-16
#include <vector>
#include <iostream>
#include <string>
using namespace std;
#include <vector>
#include <iostream>
#include <string>
using namespace std;
// Template-template argument must
// be a class; cannot use typename:
template<typename T, template<typename> class C>
void print2(C<T>& c) {
  copy(c.begin(), c.end(),
       ostream_iterator<T>(cout, " "));
  cout << endl;
}
int main() {
  vector<string> v(5, "Yow!");
  print2(v);
} ///:~

这段代码对我来说看起来很完美。但是此代码段无法在"我的 Mac"中编译。错误信息如下

 note: candidate template ignored: substitution failure [with T = std::__1::basic_string<char>]: template template argument has
      different template parameters than its corresponding template template parameter
   void print2(C<T>& c) {
         ^
    1 error generated.

这是因为std::vector不是单参数模板。标准要求std::vector的元素类型和分配器类型参数。

如果您不在旧版C++并且可以使用可变参数模板,则可以像这样声明函数:

template<typename T, template<typename...> class C>
void print2(C<T>& c);