Bypass access specifiers with C ++ 0x decltype

Consider the following code:

class A
{
private:
    class B {};
public:
    B f();
};

A a;

A::B g()
{
    return a.f();
}

The compiler rejects this - g cannot return A :: B because A :: B is private.

But suppose now I use decltype to indicate the return value of g:

class A
{
private:
    class B {};
public:
    B f();
};

A a;

decltype(a.f()) g()
{
    return a.f();
}

Suddenly it compiles fine (with g ++> = 4.4).

So I basically used decltype to get around the access specifier, whatever I was in C ++ 98.

Is it intentional? Is this a good practice?

+3
source share
1 answer

Access applies only to names (and as a special case, to constructors / destructors). This does not apply to the entities themselves. Spectrum clarifies

[ : , typedef, typedef. , typedef, . ,

class A {
  class B { };
public:
  typedef B BB;
};

void f() {
  A::BB x; // OK, typedef name A::BB is public
  A::B y; // access error, A::B is private
}

- ]

, , , . A::B ++ 03, f, &A::f , .

+5

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


All Articles