gpt4 book ai didi

c++ - 为什么编译器会选择模板参数列表中的基类构造函数?

转载 作者:IT老高 更新时间:2023-10-28 22:59:30 25 4
gpt4 key购买 nike

this one 提出后续问题.

基本上,在下面的代码中,为什么编译器会认为 B里面 A<B>C s 构造函数是指 B 的(不可访问的)构造函数基类?

struct B{};

template <typename T>
struct A : private T{};

struct C : public A<B>{
C(A<B>); // ERROR HERE
};

Live example on Ideone.输出:

prog.cpp:1:9: error: 'struct B B::B' is inaccessible
prog.cpp:7:7: error: within this context

请注意,如果将构造函数参数更改为 A<B*>,则会弹出相同的错误。 , A<B&>甚至A<const B> .另请注意,MSVC10、GCC 4.7 和 Clang 3.1 ToT 中的三个将出错,因此它必须是 C++ 规范中的内容。 这是什么?

最佳答案

该标准允许注入(inject)的类名称比原始名称更难访问。这甚至在第 11.1/5 节的注释中提到,并附有一个示例:

[ Note: In a derived class, the lookup of a base class name willfind the injected-class-name instead of the name of the base class inthe scope in which it was declared. The injected-class-name might beless accessible than the name of the base class in the scope in whichit was declared. —end note ]

[ Example:

class A { };
class B : private A { };
class C : public B {
A *p; // error: injected-class-name A is inaccessible
::A *q; // OK
};

end example ]

访问 A 不合格使用注入(inject)的名称,该名称不可访问,因为它来自私有(private)继承。访问 A 限定使用声明的名称,该名称可在全局范围内访问。

关于c++ - 为什么编译器会选择模板参数列表中的基类构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9223441/

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