gladiator
gladiator

Reputation: 13

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;
}

Upvotes: 1

Views: 80

Answers (1)

R Sahu
R Sahu

Reputation: 206737

What's common between a function pointer of type void (*)(int& m) and an instance of TEST?

They are callable with an argument of type int&.

What's the difference?

They are two different types. Unless you use a function template, they cannot be used interchangeably.

Hence, the solution for you is to use a function template.

template <typename Callable>
void f(int& n, Callable c )
{
   c(n);
}

Upvotes: 4

Related Questions