Diamond of death and Scope resolution operator (c++)

后端 未结 3 500
遇见更好的自我
遇见更好的自我 2021-01-11 10:55

I have this code (diamond problem):

#include 
using namespace std;

struct Top
{
    void print() { cout << \"Top::print()\" << e         


        
3条回答
  •  失恋的感觉
    2021-01-11 11:37

    The scope resolution operator is left-associative (though it doesn't allow parentheses).

    So whereas you want to refer to A::tell inside B, the id-expression refers to tell inside B::A, which is simply A, which is ambiguous.

    The workaround is to first cast to the unambiguous base B, then cast again to A.

    Language-lawyering:

    [basic.lookup.qual]/1 says,

    The name of a class or namespace member or enumerator can be referred to after the :: scope resolution operator applied to a nested-name-specifier that denotes its class, namespace, or enumeration.

    The relevant grammar for nested-name-specifier is,

    nested-name-specifier:

        type-name ::

        nested-name-specifier identifier ::

    So, the first nested-name-specifier is B:: and A is looked up within it. Then B::A is a nested-name-specifier denoting A and tell is looked up within it.

    Apparently MSVC accepts the example. Probably it has a nonstandard extension, to resolve ambiguity by backtracking through such specifiers.

提交回复
热议问题