C++ Logo

std-proposals

Advanced search

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

From: ஜெய்கணேஷ் குமரன் <jaiganesh.kumaran_at_[hidden]>
Date: Tue, 6 Feb 2024 17:08:24 +0000
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.

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;

Now of course, there is not much reason to use f.func_ptr, instead of just the this pointer directly, within the function. It does, however, offer some convenience when you previously had to pass in the this pointer along with the function pointer.

Received on 2024-02-06 17:08:30