C++ Logo


Advanced search

[std-proposals] Fwd: Simplify taking pointer to non-static member function

From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, 6 Feb 2024 12:56:20 -0500
---------- Forwarded message ---------
From: Jason McKesson <jmckesson_at_[hidden]>
Date: Tue, Feb 6, 2024 at 12:55 PM
Subject: Re: [std-proposals] Simplify taking pointer to non-static
member function
To: ஜெய்கணேஷ் குமரன் <jaiganesh.kumaran_at_[hidden]>

On Tue, Feb 6, 2024 at 12:08 PM ஜெய்கணேஷ் குமரன்
<jaiganesh.kumaran_at_[hidden]> wrote:
> If you're in a context where `function` results in a non-static,
> non-overloaded member function, then `&function` will result in a
> pointer to that function.
> Unfortunately no, this does not work; you must qualify it with the class name.
> From cppreference:
> Expressions such as &(C::f) or &f inside C's member function do not form pointers to member functions.

Well, the three major compilers disagree: https://gcc.godbolt.org/z/ddMbecv84

It could be bugs in all of them though. It's a pretty narrow corner case.

> Personally, it was a mistake for C to have functions naturally decay
> into function pointers, and it's good that C++ doesn't continue that
> beyond C compatibility. `&` is not that hard to write and does not
> constitute meaningful verbosity. It also adds clarity, since you don't
> have to remember how decaying works.
> Well, C++ also has function references. These should be createäble implicitly. The mistake then is being able to convert a function reference into a function pointer without writing '&' - cannot do anything now.
> Another thing I would like to have is getting a structure containing both the 'this' pointer and the function pointer when taking a member-function pointer while being inside another member function. This would simply lots of event-handling code where you may have to pass in (this, &class_name::handler) currently.
> You can write a (template) type that does this easily enough. Though
> it wouldn't work with overloading.
> Sorry, but I am not sure if this is possible. I want something like this:
> auto f = &class_name::function;
> class_name* p = f.this_ptr;

That doesn't make any sense. Member pointers are not associated with
any particular instance. That's kind of the point.

If you want to bundle a member pointer with a particular instance,
that's doable, but it would not look like that. You'd do something
like this:

auto f = mem_ptr_and_instance(this, &class_name::function);
class_name *p = f.this_ptr();

The point being that `mem_ptr_and_instance` can be a standard library
function or class; it's not too difficult to implement it as such.

Received on 2024-02-06 17:56:32