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

标签 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: 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/

相关文章:

c++ - boost IPC Message_Queue try_receive 抛出 interprocess_exception::library_error

Android NDK 应用程序 - 集成文本文件进行部署的最佳方式

c++ - 如何使此函数使用 getline 读取字符串并使其与 int 的行为相同?

c++ - 单击按钮查看图像。 qt

c++ - 检测类型是否为关联容器

c++ - 多个模板<int>函数的特化

C++11:仿函数的 return_type(对于 std::bind),其中返回类型基于输入类型

c++ - 编译器差异 : Interaction between alias resolution and name lookup

c++ - 类扩展 GtkWindow

c++ - 一个线程写入的值是否保证在不锁定该变量的情况下被另一个线程看到?