gpt4 book ai didi

c++ - 什么时候可以将模板专门用于私有(private)成员类型?

转载 作者:可可西里 更新时间:2023-11-01 18:36:47 25 4
gpt4 key购买 nike

给出这些定义

template<class T> class foo {};
template<class T> class foo1 { static int i; };
class bar { class baz {}; };

我很惊讶地看到这个编译

template<>
class foo<bar::baz> {};

但这失败并出现错误 'class bar::baz' is private

template<>
int foo1<bar::baz>::i = 42;

这种情况何时发生,除了公开类型之外是否有解决方法?

最佳答案

考虑 CWG #182 :

Certain access checks are suppressed on explicit instantiations. 14.7.2 [temp.explicit] paragraph 8 says […] I was surprised that similar wording does not exist (that I could find) for explicit specializations. I believe that the two cases should be handled equivalently in the example below (i.e., that the specialization should be permitted).

template <class T> struct C {
void f();
void g();
};

template <class T> void C<T>::f(){}
template <class T> void C<T>::g(){}

class A {
class B {};
void f();
};

template void C<A::B>::f(); // okay
template <> void C<A::B>::g(); // error - A::B inaccessible

[…]

Rationale (October 2002):

We reconsidered this and decided that the difference between the two cases (explicit specialization and explicit instantiation) is appropriate. The access rules are sometimes bent when necessary to allow naming something, as in an explicit instantiation, but explicit specialization requires not only naming the entity but also providing a definition somewhere.

GCC 和 Clang 确实拒绝了所示示例的最后一行,这显然是不一致的行为,至于类模板的相应显式特化,它们不会发出错误消息:

template <class> struct T {
void g();
};

class A { class B; class C; };

template <> struct T<A::B>; // Ok
template <> void T<A::C>::g(); // Error

Demo .因此,我会在这里走出困境,并称您在 §14.3/3 之前表现出的两种情况都不正常:

The name of a template-argument shall be accessible at the point where it is used as a template-argument.

关于c++ - 什么时候可以将模板专门用于私有(private)成员类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31033068/

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