C++:嵌套模板类错误"explicit specialization in non-namespace scope"

C++: Nested template classes error "explicit specialization in non-namespace scope"

本文关键字:explicit specialization non-namespace scope in 错误 嵌套 C++      更新时间:2023-10-16

以下代码:

template <class T1>
struct A1
{
  template <int INDEX>
  struct A2 { /* ... */ };
  template <>
  struct A2<-1> { /* ... */ };
};
int main() 
{
  A1<int>::A2<-1> x;
}

出现以下错误:

prog.cpp:7:13:错误:非命名空间作用域'struct A1<T1>'中的显式专用化prog.cpp:8:10:错误:部分专用化中未使用模板参数:
prog.cpp:8:10:错误:'T1'

如何最好地解决此错误?我试过这个:

template <class T1>
struct A1
{
  template <int INDEX, class DUMMY = void>
  struct A2 { /* ... */ };
  template <class DUMMY>
  struct A2<-1, DUMMY> { /* ... */ };
};
int main() 
{
  A1<int>::A2<-1> x;
}

这似乎奏效了,但也有点像一个软糖。

有没有更好的方法来解决这个问题?

我查阅了以前的答案,只能在类中找到具有函数的答案,而不能在类中查找。我在其他答案中也发现了"假人"的把戏,但我想知道是否有更好的解决方案。

另外,作为旁注,C++允许的第一个代码是0x吗?

不允许在不专门化A1的情况下显式专门化A2(§14.7.3/18)。C++0x具有相同的限制(n3242§14.6.3/16)。同时允许嵌套类的部分专门化。所以使用伪类的技巧是好的。