模板模板代码无效

时间:2012-12-20 14:41:03

标签: c++ templates

我正在使用gcc / 4.7,我需要在模板函数(或成员函数)中使用template-template参数实例化一个类。我收到以下错误

test.cpp: In function 'void setup(Pattern_Type&)':
test.cpp:17:34: error: type/value mismatch at argument 1 in template parameter list for 'template<template<class> class C> struct A'
test.cpp:17:34: error:   expected a class template, got 'typename Pattern_Type::traits'
test.cpp:17:37: error: invalid type in declaration before ';' token
test.cpp:18:5: error: request for member 'b' in 'a', which is of non-class type 'int'

通过注释代码段中标记的两行代码运行,因此A a可以在'main'中实例化,但不能在'setup'中实例化。我认为这对其他人也很感兴趣,我很乐意理解代码不起作用的原因。这是代码

struct PT {
  template <typename T>
  struct traits {
    int c;
  };
};

template <template <typename> class C>
struct A {
  typedef C<int> type;
  type b;
};

template <typename Pattern_Type>
void setup(Pattern_Type &halo_exchange) {
  A<typename Pattern_Type::traits> a; // Line 17: Comment this
  a.b.c=10; // Comment this
}

int main() {
  A<PT::traits> a;

  a.b.c=10;

  return 0;
}

感谢您的任何建议和解决方法! 莫罗

1 个答案:

答案 0 :(得分:9)

您需要将Pattern_Type::traits标记为模板:

A<Pattern_Type::template traits> a;

这是必需的,因为它取决于模板参数Pattern_Type

您也不应该使用typename因为traits是模板,而不是类型。