chrise
chrise

Reputation: 4253

c++ passing function itself as argument

I have a containerclass that holds various objects in a map that have similar getter functions. That is itself contained in a class that uses that data. so, I have a bit of a chain here which seems not ideal.

class Obj {
    double getA() { return m_a; }
    double getB() { return m_b; }
    ....

    double m_a, m_b, ...;
}

class Container {
    map<long, Obj> m_objs;

    getA( int i ) { return m_objs[i].getA(); }
    getB( int i ) { return m_objs[i].getB(); }
}

class User {
    Conainer m_cont;
    getA( int i ) { return m_cont.getA( i ); }

Is there a more generic way to get the objects values by somehow passing the calling function into it. I admit the whole construct with the long chain doesnt seem ideal, but in that context it seems natural because I have some sort of tree of objects and carry information upwards to the top node and I would not know how to avoid this. But if there are any suggestions of a better way to deal with this, I am happy to hear it

Upvotes: 1

Views: 352

Answers (1)

The Vee
The Vee

Reputation: 11550

The object you would need to pass in this scenario is a pointer to member function:

class Obj {
  // ...

  double getA() {
    return a;
  }

  double getB() {
    return b;
  }

private:
  double a;
  double b;
};

class Container {
  // ...
  get(int i, double (Obj::*what)()) { return (m_objs[i].*what)(); }
};

class User {
  Container m_cont;
  // ...
  get(int i, double (Obj::*what)()) { return m_cont.get(i, what); }
};

// ...
double myA = user.get(1, &Obj::getA);

You can also add this to Obj:

double get(double (Obj::*what)()) {
  return (this->*what)();
}

to make Container more consistent with User:

class Container {
  // ...
  get(int i, double (Obj::*what)()) { return m_objs[i].get(what); }
};

Upvotes: 2

Related Questions