0
class Test{
    int data1;
    int data2;
public:
    Test(int a=0, int b=0): data1(a), data2(b) {}
    int geta() const { return data1; }
    int getb() const { return data2; }
};

class List{
    struct ListNode{
        Test data;
        ListNode *next;
        ListNode(ListNode *p = NULL) :next(p) {}
    };
    ListNode *first, *iter;
public:
    List(){ iter = first = new ListNode; }
    void add(const Test& dat){...}

//******************************************
    int geta() { return iter->data.geta(); }
    int getb() { return iter->data.getb(); }
    template <typename S>
    void fgv(S pred){
        while(iter->next!=NULL){
            cout << pred << endl;
            iter=iter->next;
        }
    }
//******************************************

    ~List(){...}

};

int main()
{
    Test a(33, 75);
    Test b(55, 36);
    Test c(66, 21);
    List l;
    l.add(a);
    l.add(b);
    l.add(c);

//*****************
    l.fgv(l.geta);
    l.fgv(l.getb);
//*****************

So I have a list, which stores "Test" classes, and the list also has two get() functions. What I wanted to do is a function ( void fgv(S pred) ), which gets a member function (for now its either geta() or getb() ) in its parameter, then it goes through the list and prints out the int values that either geta() or getb() returns. Is there a simple way to do this?

  • Take a look at member function pointers: https://isocpp.org/wiki/faq/pointers-to-members – Jonathan S. May 06 '22 at 23:58
  • Calling a pointer to member function has tricky syntax. See https://stackoverflow.com/questions/14814158/c-call-pointer-to-member-function – zdan May 07 '22 at 00:21

0 Answers0