C ++中的模板模板参数

时间:2016-05-12 20:35:34

标签: c++

#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);
} ///:~

这段代码看起来很完美。但是这个代码片段无法在My 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.

1 个答案:

答案 0 :(得分:4)

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

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

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