是否可以使用指向成员的指针来获取实际的指针? [英] Is it possible to use a pointer-to-member to get an actual pointer?

查看:149
本文介绍了是否可以使用指向成员的指针来获取实际的指针?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些结构或类 example ,我需要发送一个指针到其任何一个成员。

I have some struct or class example, and I need to send a pointer to any of its members somewhere.

void send_ptr(void *ptr, std::size_t size);

struct obj {};

struct example {
    int a;
    obj b;

private:
    static void send_ptr(void *ptr, std::size_t size) {}

public:
    template <typename M>
    void send_member(M *member) {
        send_ptr(member, sizeof(M));
    }

这很好,但我想我可以使用指针到成员介绍一些小静态检查。 ( send_member 的上述实现实际上可以发送任意指针。)

This works fine but I thought I could use pointer-to-member here to introduce a little static checking. (The above implementation of send_member can actually send an arbitrary pointer.)

    template <typename M>
    void send_member(M example::*member) {
        send_ptr(&this->*member, sizeof(M));
    }
};

这会失败,因为指针成员取消引用( this-> *

This fails because pointer-to-member dereference (this->*member) apparently evaluates to an rvalue.


error: lvalue required as unary ‘&’ operand
        send_ptr(&this->*member, sizeof(M));
                  ^

现在,我以为我可以聪明和尝试

Now, I thought I could be clever and tried

&static_cast<M &>(this->*member)

这似乎工作,但老实说,我不完全明白如何。也许是不安全的。我知道 static_cast 可以这种方式使用(有时像完美转发),但我不完全理解这里的语义。

This appears to work but to be honest, I don't fully understand how. Maybe it's unsafe. I know that static_cast can be used this way sometimes (like perfect forwarding) but I don't fully understand the semantics here.

那么是否可以使用指针到成员可靠地获取指向成员的实际指针? static_cast 是否有效(如果是这样,你能解释一下)?

So is it possible to use a pointer-to-member to reliably get an actual pointer to the member? Does the static_cast work (if so, could you explain how)? Or is there a simpler way?

推荐答案

运算符& operator-> * 运算符优先级 $ c>和运算符。& 将绑定到 this ,这是一个 prvalue ,而不是 glvalue 其中你可以取地址。使用括号来排序评估:

operator& has greater operator precedence than operator->* and operator.*. The & will bind to this first which is a prvalue, not a glvalue of which you can take the address. Use parentheses to sequence the evaluation:

send_ptr(&(this->*member), sizeof(M));

这篇关于是否可以使用指向成员的指针来获取实际的指针?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆