问题
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));
}
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 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)
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.
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?
回答1:
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));
来源:https://stackoverflow.com/questions/27724971/is-it-possible-to-use-a-pointer-to-member-to-get-an-actual-pointer