简体   繁体   中英

C++ Can I pass the choice of member function as argument?

I have a class with two member functions getA and getA2 , that do a similar thing. They both return an int after an internal computation that might differ.

In the function printStuff I call both, but I actually only want to call one of them, but without naming it in printStuff . I want to give printStuff the information of which member function of class A to use in its body as an argument to printStuff somehow.

class A {
public:
  A(int a) : m_a(a) {;}
  int getA() {
    return m_a;
  };
  int getA2() {
    return 2*m_a;
  };

private:
  int m_a = 0;

};

void printStuff(/*tell me which member fcn to use*/) {
  A class_a(5);

  //I actually just want to call the last of the 2 lines, but define somehow
  //as an argument of printStuff which member is called
  cout << "interesting value is: " << class_a.getA() << endl;
  cout << "interesting value is: " << class_a.getA2() << endl;
  cout << "interesting value is: " << /*call member fcn on class_a*/ << endl;
}

int functional () {

  printStuff(/*use getA2*/); //I want to decide HERE if getA or getA2 is used in printStuff
  return 0;
}

Can it be done somehow? From reading on function pointers I am not sure how I could apply this here correctly.

You can do the parametrization you want by passing a pointer to a member function .

void printStuff( int (A::* getter)() ) {
  A class_a(5);

  cout << "interesting value is: " << (a.*getter)() << endl;
}

// in main
printStuff(&A::getA2);

The declarator syntax int (A::* getter)() is a bit wonky in true C++ fashion, but that's how you use a raw pointer-to-member function in a function's signature. A type alias may simplify the syntax a bit, so it's worth keeping that mind. And I think &A::getA2 is pretty self-explanatory.

Also be mindful of the parentheses in (a.*getter)() , since operator precedence requires it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM