Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a context where the expression `a.b::c` makes sense?

Tags:

c++

In C++ consider the grammar rule:

member-access-expression: LHS member-access-operator RHS
(op is .)
and
LHS=unqualified id-expression e.g. that references an instance variable.
RHS=qualified id-expression (with at least one nested identifier)

example: a.b::c

If that can ever pass the semantic check, what situation would it be ?

The following experiment:

struct B{};

struct A
{
    B b;
};

int main()
{
    A a;
    a.b::c;
}

returns

'b' is not a class, namespace, or enumeration
a.b::c;
  ^

(demo)

This tends to hint to me that there can't be any legal case of a qualified-id on the right of a member access.

like image 703
v.oddou Avatar asked May 22 '19 09:05

v.oddou


3 Answers

A very simple example is if you want to call a member function of a parent class:

struct A {
    void f();
};

struct B: A {
    void f();
};

B b;
b.A::f();
like image 110
Holt Avatar answered Oct 13 '22 22:10

Holt


One use case is accessing members of an enum within some struct A by using an instance of A (rather than using the enum directly via A::b::c):

struct A {
    enum class b { c }; // can be unscoped as well
};

A a;
a.b::c; // Access to enum value c - similarly, A::b::c would work
like image 43
andreee Avatar answered Oct 14 '22 00:10

andreee


Here's a trivial example:

struct A {
    void f() {}
};

int main()
{
    A a;
    a.A::f();
}

A::f() is a qualified version of the name for the function f that's a member of A. You can use it in member access just like the "short" (or unqualified) name.

In fact, one might argue that every time you write a.f(), that's a shortcut for a.A::f() (with the A:: part being taken automatically from decltype(a)).

There's nothing magic about this, though it's unusual to see the construct outside of the sort of scenarios the other answerers demonstrated, because in this example it's redundant.

like image 35
Lightness Races in Orbit Avatar answered Oct 14 '22 00:10

Lightness Races in Orbit