c++ - 这篇 cppreference.com 文章的结尾有问题

标签 c++ templates specialization

我已阅读 What does template's implicit specialization mean?和它的答案,但我仍然不满意我理解这部分Partial template specialization来自 cppreference.com:

If the primary member template is explicitly (fully) specialized for a given (implicit) specialization of the enclosing class template, the partial specializations of the member template are ignored for this specialization of the enclosing class template....

template<class T> struct A { //enclosing class template
  template<class T2>
  struct B {};  //primary member template
  template<class T2>
  struct B<T2*> {};  // partial specialization of member template
};
         
template<>
template<class T2>
struct A<short>::B {}; // full specialization of primary member template
                       // (will ignore the partial)
        
A<char>::B<int*> abcip; // uses partial specialization T2=int
A<short>::B<int*> absip; // uses full specialization of the primary (ignores partial)
A<char>::B<int> abci; // uses primary

问题:
  • 评论说这条线template<> template<classT2> struct A<short>::B {};是“主要成员模板的完全特化”。主要成员模板在注释中标识为结构 B .线怎么会是B的专业当它是A正在通过替换 short 专门化为 class T ?
  • 线下怎么能“全”专精B当模板参数T2未指定?
  • 注释和随附的文本表明“显式特化”和“完全特化”是同义词。如果上面引用的代码行是 B 的显式特化,其中是 A 的隐式特化?
  • 最佳答案

    类模板的成员可以显式特化,即使它是 不是模板 :

    template<int I>
    struct X {
      int f() {return I;}
      void g() {}
    };
    template<>
    int X<0>::f() {return -1;}
    
    这相当于专门化了整个类模板,但具有其他成员 重复 来自相关的主要模板或部分特化:
    template<>
    struct X<0> {
      int f() {return -1;}
      void g() {}
    };
    
    (回想一下,这样一个拼写出来的特化完全没有义务声明 g 或作为一个函数。)因为你实际上没有写这个,它仍然被认为是一个 隐式 X 的实例化作为一个整体与给定的改变。
    这就是为什么您的特化A<T>::BA 提供模板参数而不是为 B ;它是 更换 模板A<T>::B与另一个模板(恰好具有相同的模板参数列表)。我会说“主要”这个词在这里有误导性:它是整个模板被替换,这就是为什么 A<short> 忽略部分特化的原因。此后。

    关于c++ - 这篇 cppreference.com 文章的结尾有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64507071/

    相关文章:

    c++ - vector 、迭代器和 std::find

    c++ - std::move 对堆栈变量有意义吗

    c++ - 如何在没有运行时开销的情况下轻松配置类?

    c# - 如何在 C# 中实现某种程度的多态性?

    c++ - 模板实例化——编译器如何避免重复符号?

    c++ - 如何将 `CString` 转换为 `CHAR *` ?

    C++:当使用从对象的getter方法调用的值时,输出一个随机的负整数?

    c++ - 为什么不能使用 [[deprecated]] 弃用模板?

    C++ 链接和模板特化

    不允许 C++ 函数特化?