简体   繁体   English

使用C ++ 0x decltype来访问访问说明符

[英]Getting around 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. 编译器拒绝这个 - g不能返回A :: B,因为A :: B是私有的。

But suppose I now use decltype to specify the return value of g: 但是假设我现在使用decltype来指定g的返回值:

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

A a;

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

All of a sudden it compiles fine (with g++ >= 4.4). 它突然编译得很好(g ++> = 4.4)。

So I've basically used decltype to get around an access specifier in a way I would not have been able to in C++98. 所以我基本上使用了decltype以一种我在C ++ 98中无法实现的方式来绕过访问说明符。

Is this intentional? 这是故意的吗? Is this good practice? 这是好习惯吗?

Access only applies to names (and as a special case, to constructors/destructors). Access仅适用于名称 (以及作为特殊情况,适用于构造函数/析构函数)。 It doesn't apply to entities themselves. 它不适用于实体本身。 The spec further elaborates 该规范进一步阐述

[ 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. [注意:由于访问控制适用于名称,如果将访问控制应用于typedef名称,则仅考虑typedef名称本身的可访问性。 The accessibility of the entity referred to by the typedef is not considered. 不考虑typedef引用的实体的可访问性。 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 ] - 结束说明]

So what you have disovered here isn't surprising. 所以你在这里发现的并不奇怪。 You can get hold of the type A::B even in C++03, when taking the address of f by saying &A::f and passing it to a function template deducing the return type. 即使在C ++ 03中也可以获得类型A::B ,当通过说&A::f并将其传递给函数模板推断返回类型来获取f的地址时。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM