c++ - 类范围内的类模板特化?

标签 c++ templates nested-class specialization

为什么 A 中的特化 S 合法而 B 中的 S 不合法?

(如果 B 没有被注释掉) GCC 4.8.1:错误:在非 namespace 范围“B 类”中的显式特化

#include <type_traits>
#include <iostream>

class Y {};
class X {};

struct A {
  template<class T, class = void>
  class S;

  template<class T>
  struct S < T, typename std::enable_if< std::is_same< Y, T >::value >::type > 
  {
    int i = 0;
  };

  template<class T>
  struct S < T, typename std::enable_if< std::is_same< X, T >::value >::type > 
  {
    int i = 1;
  };
};

/*
class B
{
    template<class T>
    class S;

    template<>
    class S < Y > {};

    template<>
    class S < X > {};
};
*/


int main()
{
    A::S< X > asd;
    std::cout << asd.i << std::endl;
}

on coliru: B commented out

on coliru: with B (error)

最佳答案

@jrok 的评论几乎可以解释您的编译器错误。一般而言,嵌套类,尤其是嵌套类模板,是您可以轻松避免的语言的一个尘土飞扬的角落(牢记 Sutter 的建议“Write what you know and know what you write”)。

简单地制作一个命名空间细节来定义你的类模板SASB及其特化,然后定义一个嵌套的模板类型别名SAB

namespace detail {

  template<class T, class = void>
  class SA;

  template<class T>
  struct SA < T, typename std::enable_if< std::is_same< Y, T >::value >::type > 
  {
    int i = 0;
  };

  template<class T>
  struct SA < T, typename std::enable_if< std::is_same< X, T >::value >::type > 
  {
    int i = 1;
  };

  template<class T>
  class SB;

  template<>
  class SB < Y > {};

  template<>
  class SB < X > {};
}

struct A
{
    template<class T>
    using S = detail::SA<T>;
};

struct B
{
    template<class T>
    using S = detail::SB<T>;
};

诚然,对于这种情况,这似乎有点过分了,但是如果你想自己制作 AB 类模板,并专门化 AB,那么如果您还特化了封闭类,则只能特化嵌套类模板。简而言之:只需通过额外的编译时间接级别来完全避免这些问题。

关于c++ - 类范围内的类模板特化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18904587/

相关文章:

c++ - 模板继承矩阵和方阵C++

c++ - 嵌套类和构造函数调用理解

c++ - 从类本身运行函数

c++ - 在不明确的情况下使用限定 ID 访问类成员

c++ - initializer_list 和 move 语义

java - 为什么要使用与它们所在的当前类相同类型的变量?

java - 静态嵌套类访问抛出 NoClassDefFoundError

C++模板题

c++ - MPI_Op_create : candidate function not viable. 自定义结构指针不能解释为空指针

ruby-on-rails - Partial, Layout, Template 渲染问题