C ++:嵌套模板类错误“非命名空间范围中的显式特化”

时间:2011-06-10 04:23:46

标签: c++ templates c++11

以下代码:

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;
}

这似乎有用,但似乎也有点像软糖。

有更好的解决方法吗?

我查看了以前的答案,只能在课堂上找到函数,而不是在类中找到函数。我还在其他答案中找到了“DUMMY”技巧,但想知道是否有更好的解决方案。

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

1 个答案:

答案 0 :(得分:11)

如果没有专门化A2(§14.7.3/ 18),则不允许明确专门化A1。 C ++ 0x具有相同的限制(n3242§14.7.3/ 16)。同时,允许嵌套类的部分特化。因此,使用虚拟类的技巧是好的。