1

This may kind of odd but I do have this case in my job.

Say I have a function:

A->fucntion();

And this function will be passed as a parameter to another function

(func(A->function);)

My question is how to get variable A in the func()?

I am new to c++, thank you for any advice!

wohlstad
  • 12,661
  • 10
  • 26
  • 39
keviniskw
  • 19
  • 3
  • Are you looking for pointer-to-member? https://en.cppreference.com/w/cpp/language/pointer – Nimrod Jul 27 '22 at 09:15
  • 3
    Pass the object pointed to by `A` as a separate argument? – Some programmer dude Jul 27 '22 at 09:15
  • 2
    Also note that with `func(A->function())` you *call* `A->function()` and pass the result to `func()`. You don't actually pass the function `function`. – Some programmer dude Jul 27 '22 at 09:16
  • apart that the syntax is incorrect: should be `func(A->function);`... what you want to do cannot be done – Marco Beninca Jul 27 '22 at 09:16
  • 1
    Refer to a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list). – Jason Jul 27 '22 at 09:19
  • It's a little clearer now... I would probably use a [*lambda*](https://en.cppreference.com/w/cpp/language/lambda), like `func([&]() { A->function(); });` or `func([&]() { B->function(); });`. Then `func` doesn't need to do anything special at all, and call just call `action`. – Some programmer dude Jul 27 '22 at 10:19
  • Provide a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). – Jason Jul 27 '22 at 12:49
  • 2
    @keviniskw you should not change your question after you have valid answer(s) in a way that invalidates them. Therefore I rolled back your changes. You should ask a new question instead. – wohlstad Jul 29 '22 at 04:20

1 Answers1

1

2 relevant issues:

  1. You will need to pass your instance (A) as an additional parameter. Without it you will not be able to invoke a pointer-to-member.

  2. You will also need to use the syntax to invoke a method via a pointer-to-member.

See a complete example:
(used A for the class name and a for the instance, as it's more common)

#include <iostream>

struct A
{
    void function() 
    { 
        std::cout << "A::function()" << std::endl; 
    }
};


// Type of a pointer to a method of class A:
typedef void (A::* AsMethod)();


//--------vvvv------------------- (add parameter for the instance)
void func(A& a, AsMethod aMethod)
{
    // Invoke a method via pointer-to-member:
    (a.*aMethod)();
}


int main()
{
    A a;
//-------v---------------- ) (pass the instance)
    func(a, &A::function);
}

Output:

A::function()
wohlstad
  • 12,661
  • 10
  • 26
  • 39