【问题标题】:Class template specialization in class scope?类范围内的类模板专业化?
【发布时间】:2013-09-25 02:56:42
【问题描述】:

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

(如果 B 没有被注释掉) GCC 4.8.1:错误:非命名空间范围“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 你能详细说明一下吗? This 的回答似乎不同意。

标签: c++ templates nested-class specialization


【解决方案1】:

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

只需创建一个namespace detail 来定义您的类模板SASB 及其特化,然后在AB 中定义嵌套模板类型别名S

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,那么您只能专门化嵌套类模板如果您还专门研究封闭类。简而言之:只需通过额外级别的编译时间接来完全避免这些问题。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多