Why doesn't private inheritance disambiguate for static functions? (verified by MSVC)

I am wondering why calling a static function is ambiguous, even if one of the two is obviously impossible to name, since it is private. I was hoping I could use private / secure inheritance to help the compiler resolve this ambiguity.

Is this specific to MSVC or is it somehow specified in the standard?

struct A { static int num() { return 0; } }; struct B { static int num() { return 1; } }; struct C : public A, private B {}; int main() { C::num(); // Ambiguous access of num } 

The background is that I tried to reuse overload behavior (one of A) in many derived classes (C, D, E, F, G), inheriting it, somehow sticking to Don’s rule. Repeat for yourself.

+5
source share
3 answers

Yes, this is stated in the C ++ standard, section Β§3.4 [basic.lookup]

Access rules (section 11) are considered only after a successful name search and permission to overload the function (if applicable)

A search by name does not care about accessibility: it finds both A::num and B::num , so there is ambiguity for the compiler.

You can explicitly call A::num with:

 C::A::num(); 

If you are explicitly trying to call B::num , then your compiler will indeed throw an access error:

 C::B::num(); // Error 

You can also explicitly enter the base name in the scope in the derived class, which eliminates the ambiguity:

 struct C : public A, private B { using A::num; }; 
+6
source

To help the compiler, you can do this

  struct C : public A, private B { using A::num; }; 
+3
source

Private members are deliberately taken into account when allowing congestion.

Suppose you have

 class C { public: static void f(int); static void g(); private: static void f(long); }; void C::g() { f(0L); // okay } void g() { f(0L); // error, does not silently call f(int) } 

Providing only open items while overload resolution causes a very unexpected re-interpretation of the code, where code that looks like it should work in exactly the same way would silently cause different overloads.

When creating such code, the error was considered less difficult than the alternative.

+1
source

Source: https://habr.com/ru/post/1210003/


All Articles