简体   繁体   English

推导类型的基类成员的指针

[英]Deduced type for pointer-to-member of base class

#include <type_traits>

struct BaseClass
{
    int baseValue;
};

struct DerivedClass : public BaseClass
{
    int derivedValue;
};

int main()
{
    auto memDataPtr = &DerivedClass::baseValue;

    static_assert(std::is_same<decltype(memDataPtr), int BaseClass::*>::value, "Huh?");
}

All the compilers I've tried this on compile this code successfully, ie, the static assert does not fire. 我尝试过的所有编译器都成功地编译了此代码,即,静态断言不会触发。 This means that if I take the address of a member inherited from a base class, the resultant pointer-to-member refers to the base class the member comes from, even if I explicitly use the derived class name when specifying the member. 这意味着,即使我在指定成员时显式使用派生的类名称,如果我采用从基类继承的成员的地址,则指向成员的结果指针将指向该成员所属的基类。

I'm curious to know where in the spec this is explicitly called out, and the reasoning behind this behavior, as it seems a bit counter-intuitive (to my naive self at least). 我很好奇,在规范中明确指出了它的位置,以及这种行为背后的原因,因为这似乎有点违反直觉(至少对我天真的我而言)。

See [expr.unary.op], which says 参见[expr.unary.op],其中说

If the operand is a qualified-id naming a non-static or variant member m of some class C with type T, the result has type “pointer to member of class C of type T” and is a prvalue designating C::m. 如果操作数是命名类型为T的某些类C的非静态或变体成员m的合格ID,则结果的类型为“指向类型T的类C的成员的指针”,并且是表示C :: m的前值。

It also gives an example to show this behavior: 它还提供了一个示例来显示此行为:

struct A { int i; };
struct B : A { };
... &B::i ... // has type int A::*

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

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