gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 06:50:16 25 4
gpt4 key购买 nike

我已阅读 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com