Calling member functions using member pointers from non-member functions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;

class A
{
    void foo()
    {
        cout << "Arrived foo" << endl;
    }

    void test();
};


void baa( auto (A::*pointer_func) ())
{
    (this->*pointer_func)(); // throws an error here
}

void A::test()
{
    baa(foo);
}

int main()
{
    
}


I am trying to call the member function 'foo' from the non-member function 'baa' but it throws me this error

|18|error: invalid use of 'this' in non-member function|

I understand this error as it is pretty straightforward, but I just don't know how to fix it. If I can not use 'this' in non-member function then can use something else to achieve this goal?
Last edited on
The "this" is a pointer. The baa does not have it, so it should be given one:
1
2
3
4
5
6
7
8
9
void baa( A* a, auto (A::*pointer_func) ())
{
    (a->*pointer_func)();
}

void A::test()
{
    baa( this, foo );
}

However, that might not be correct syntax either and a more profound question is: Is this the correct X to solve Y?
@keskiverto thanks, that worked.

That profound question though, I didn't get it.
Topic archived. No new replies allowed.