c++functionargument-passing

c++ Functions (with body) as Argument


I want to pass an function as argument. I know you can pass a function pointer like the first test in my example, but is it possible to pass a hold function (not a pointer) like my second test?

#include <iostream>

using namespace std;


/* variable for function pointer */
void (*func)(int);

/* default output function */
void my_default(int x) {
    cout << "x =" << "\t" << x << endl << endl;
}


/* entry */
int main() {
    cout << "Test Programm\n\n";

    /* 1. Test - default output function */
    cout << "my_default\n";
    func = &my_default;   // WORK! OK!
    func(5);

    /* 2. Test - special output function 2 */
    cout << "my_func2\n";
    func =  void my_func1(int x) {
            cout << "x =" << "  " << x << endl << endl;
        };   // WON'T WORK! FAILED!
    func(5);

    return 0;
}

Solution

  • In C++ 11, you can pass a lambda:

    func = [](int x) {  cout << "x =" << "  " << x << endl << endl; };
    

    EDIT: lambdas can return values:

    func = [](int x)->int{  cout << "x =" << "  " << x << endl << endl; return x; };