KARTHIK M S
KARTHIK M S

Reputation: 115

How to get address of member function within the class without using class name for scope?

I want to know if it is possible to get the address of a member function within the class without using the class name for scope.

In the below example, inside main is the normal way of getting address, but inside func2, is there a way without using class name. The reason for asking for something like this is, in future if I change the class Name, I don't have to go and change inside. eg:

Class A
{
 void func1()
 {
 }
 void func2()
 {
  /Address of func1/ = &func1; // something like this possible?
 }
}
void main()
{
 /Address of func1/ = &A::func1;
}

Upvotes: 1

Views: 282

Answers (2)

Bathsheba
Bathsheba

Reputation: 234715

For non-static member functions,

&std::remove_reference_t<decltype(*this)>::func1

is one way.

For static functions, use std::addressof

std::addressof(func1); 

which relies on the fact that the A:: is implicit.

Upvotes: 7

P.W
P.W

Reputation: 26800

If func1 is a static function, you can use std::addressof to get its address.

class A
{
    public:
    static void func1()
    {
    }
    void func2()
    {
        auto fptr = std::addressof(func1); 
    }
};

Note: This will not work on non-static member functions.

Upvotes: 2

Related Questions