向 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
};
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 will find the injected-class-name instead of the name of the base class in the scope in which it was declared. The injected-class-name might be less accessible than the name of the base class in the scope in which it 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/