以下代码:
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: error: explicit specialization in non-namespace scope
'struct A1<T1>'
prog.cpp:8:10: error: template parameters not used in partial specialization:
prog.cpp:8:10: error:'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 是否允许第一个代码?
最佳答案
不允许在不专门化 A1
的情况下明确专门化 A2
(§14.7.3/18)。 C++0x 具有相同的限制 (n3242 §14.7.3/16)。同时允许嵌套类的部分特化。所以虚拟类的诀窍是好的。
关于C++:嵌套模板类错误 "explicit specialization in non-namespace scope",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6301966/