samedi 23 décembre 2017

Passing a function object as function argument

I would like to simply pass my initialized function object to my own function in several ways.

I did not find any examples with own functions just with "for_each" but as far as i understand it should work the same way.

void    f(int& n, void (*g)(int& m) ){ g(n);};

class TEST{
public:
    int init=0;
    TEST(int _init):init(_init){}
    void    operator() (int& m) {m+=init;}

};

int main(int argc, char *argv[])
{
    int k, m;
    cin >> k >> m;

    TEST    mytest(m); // OK, creates object with initialization
    mytest(m);         // OK, using initialized object's "operator()"

    f(k,mytest);       //  error: cannot convert 'TEST' to
                       //  'void (*)(int&)' for argument '2'to
                       //  'void f(int&, void (*)(int&))'

    f(k,TEST(m));      //  error: cannot convert 'TEST' to
                       //  'void (*)(int&)' for argument '2'to
                       //  'void f(int&, void (*)(int&))'

    return 0;
}

Aucun commentaire:

Enregistrer un commentaire