在给定模板参数的模板类类型的类中声明变量

时间:2017-02-06 12:52:00

标签: c++ templates using

我正在尝试实例化一个类中包含的模板类,该类作为模板参数给出。通过示例可能更容易理解:

struct A {
static constexpr int a = 42;

class B {
  int b;
};

template<typename X>
class C {
  X c;
};
};

template<typename U, typename T>
class D {
  int a = U::a;

  using B = typename U::B;
  B b;

  //using C = typename U::C;
  // C<T> c;
  A::C<T> e;
};


int main(void) {
  D<A, int> d;
  return 0;
}

如果我取消注释注释行,编译器会给出一个错误,表示C不是模板。我尝试了其他方法来实例化这个变量,但它没有用。我希望使用等效的e变量,但使用U类型。

1 个答案:

答案 0 :(得分:5)

请注意,您没有将C声明为模板类型,然后C<T> c会导致错误,因为您无法将其用作模板类型。

你想要的是alias template(一个类型的名称),正确的语法是:

template <typename Z>
using C = typename U::template C<Z>;

然后

C<T> c;  // same as U::template C<T>; Z is substituted with T 

使用D<A, int> d;U = AT = intC<T>DA::C<int>相同{1}}。

LIVE