0

So I simply want to pass a member function as a parameter to a member function. Obviously, this is straight forward for functions, but with member functions (non-static) I have a hard time to wrap my head around. Consequently, I want to pass this member functions of different classes. So I want the following:

#include <iostream>
#include <vector>
#include <functional>

using namespace std;

class A {
  public:
    void a(std::string somestring, int (A::*f) (int));
        int b(int i);
};

void A::a(std::string somestring, int (A::*f) (int)) {
    int i = 20;
  std::cout << somestring << " A::a()" << "\n";
    std::cout << (this->*f)(i) << "\n";
}

int A::b(int i) {
  std::cout << "B::b()" << "\n";
  return i+10;
}

class B {
  public:
    int c(int i);
};

int B::c(int i) {
  std::cout << "B::c()" << "\n";
  return i+20;
}

int main() {
    A objA;
    B objB;

    objA.a("test",&A::b);

}

This works for the same classes (A::a and A::b), but how can I achieve this for different classes (e.g., B::c as argument for A::a)?

I don't think this is a duplicate. I wan't call member functions from different Classes. These are not covered in the answers of the other questions.

riasc
  • 281
  • 2
  • 3
  • 15
  • 1
    Use templates, or [`std::function`](https://en.cppreference.com/w/cpp/utility/functional/function) with either [lambdas](https://en.cppreference.com/w/cpp/language/lambda) or [`std::bind`](https://en.cppreference.com/w/cpp/utility/functional/bind). – Some programmer dude Nov 08 '18 at 14:12
  • 2
    Or make `B::b` `static`. – Yakk - Adam Nevraumont Nov 08 '18 at 14:12
  • Thanks for the hints. However, making B::b `static` is not possible. I mean there has to be a way to get it to work with different Classes. Somehow A::a has to know about the B Class? – riasc Nov 08 '18 at 17:45

0 Answers0