gpt4 book ai didi

c++ - 使用 C++0x decltype 绕过访问说明符

转载 作者:太空狗 更新时间:2023-10-29 20:47:50 24 4
gpt4 key购买 nike

考虑以下代码:

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

A a;

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

编译器拒绝这个 - g 不能返回 A::B 因为 A::B 是私有(private)的。

但是假设我现在使用decltype来指定g的返回值:

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

A a;

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

突然之间编译正常(使用 g++ >= 4.4)。

所以我基本上使用 decltype 以一种在 C++98 中无法做到的方式绕过访问说明符。

这是故意的吗?这是好的做法吗?

最佳答案

访问仅适用于名称(作为一种特殊情况,适用于构造函数/析构函数)。它不适用于实体本身。规范进一步阐述

[ Note: because access control applies to names, if access control is applied to a typedef name, only the accessibility of the typedef name itself is considered. The accessibility of the entity referred to by the typedef is not considered. For example,

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
}

— end note ]

所以您在这里的发现不足为奇。即使在 C++03 中,您也可以通过 &A::f 获取 f 的地址来获取类型 A::B > 并将其传递给函数模板以推导返回类型。

关于c++ - 使用 C++0x decltype 绕过访问说明符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4704590/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com