Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
150 views
in Technique[技术] by (71.8m points)

c++ - Why does the compiler select the base class constructor inside the template argument list?

Follow-up question to this one.

Basically, in the following code, why does the compiler think that the B inside A<B> in Cs constructor refer to the (inaccessible) constructor of the B base class?

struct B{};

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

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

Live example on Ideone. Output:

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

Note that the same error pops up if you change the constructor argument to A<B*>, A<B&> or even A<const B>. Also note that three of MSVC10, GCC 4.7 and Clang 3.1 ToT will error out, so it must be something in the C++ spec. What is it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The standard allows injected class names to be less accessible than the original names. This is even mentioned in a note in §11.1/5, together with an example:

[ 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 ]

Accessing A unqualified uses the injected name, which is not accessible because it comes from private inheritance. Accessing A qualified uses the declared name, which is accessible in the global scope.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...