Search code examples
c++multiple-inheritancefully-qualified-naming

Ambiguity in a fully qualified static member variable


In this sample code, there is two sentences showing the same static variable. The first one gives no ambiguity, but the second one does, why?

#include <iostream>

using namespace std;

struct A { static const char a = 'a'; };
struct B : public A { };
struct C : public A { };
struct G : public B, public C { };

int main()
{
    G v;

    cout << G::B::A::a << endl;
    cout << v.B::A::a << endl;
}

GCC error (according to some comments, there's no ambiguity in clang):

main.cpp:15:18: error: 'A' is an ambiguous base of 'G'
  cout << v.B::A::a << endl;

Code on coliru


Solution

  • This is clearly a bug in GCC, as a GCC maintainer recommends you report it. However, until it's fixed, you can use a nasty workaround like this:

    std::cout << static_cast<B &>(v).A::a;
    

    The advantage is this will help disambiguate if in a (complex) scenario that there are variables with the same name in one of the base classes.