嵌套模板类:不接受参数默认值

fek*_*lee 4 c++ templates gnu g++ template-meta-programming

这样编译:

class A {
public:
  template <int, int> class B;
};

template <int y, int z = y>
class A::B {
};

int main() {}
Run Code Online (Sandbox Code Playgroud)

这不是:

template <int x>
class A {
public:
  template <int, int> class B;
};

template <int x>
template <int y, int z = y>
class A<x>::B {
};

int main() {}
Run Code Online (Sandbox Code Playgroud)

g++ main.cpp 说:(版本9.1.0)

main.cpp:24:13: error: default argument for template parameter for class enclosing ‘class A<x>::B<<anonymous>, <anonymous> >’
   24 | class A<x>::B {
      |             ^
Run Code Online (Sandbox Code Playgroud)

怎么了?

Ozn*_*nOg 7

默认参数需要在声明中:

template <int x>
class A {
public:
  template <int y, int = y> class B;
};

template <int x>
template <int y, int z>
class A<x>::B {
};

int main() {
    A<1>::B<2> b;
}
Run Code Online (Sandbox Code Playgroud)

不允许使用默认参数

在类模板成员的类外定义中(必须在类主体的声明中提供它们)。请注意,非模板类的成员模板可以在其类外定义中使用默认参数(请参见GCC错误53856)

https://en.cppreference.com/w/cpp/language/template_parameters