pizzaEatingGuy
pizzaEatingGuy

Reputation: 888

How to pass a function as parameter into another function in C++?

my compiler gives the following error. Please help me with the syntax.

int sum(int a, int b);
int sum(int a, int b) {
    return a+b;
}

int mult(int c, std::function<int(int a, int b)> sum2);
int mult(int c, std::function<int(int a, int b)> sum2) {
    return sum2 * c;
}

int main() {
    cout << mult(5, sum(2, 2));
    return 0;
}

Upvotes: 1

Views: 103

Answers (4)

BЈовић
BЈовић

Reputation: 64203

There are so many errors :

  1. missing #include <iostream> and #include <functional>
  2. cout should be std::cout
  3. multiplying functor with int makes no sense, since such operator* is not defined. Try for example this:

    int mult(int c, std::function<int(int a, int b)> sum2) {
        return sum2(2,2) * c;
    }
    int main() {
        std::cout << mult(5, sum);
    }
    

Upvotes: 0

Blacktempel
Blacktempel

Reputation: 3995

You're actually passing the value 4 to the function mult. You should do this instead:

mult (5, sum);

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409136

You're using it all wrong, you should not call the sum function in the call to mult, instead you call it in mult:

int mult(int c, std::function<int(int a, int b)> sum2) {
    return sum2(2, 2) * c;
}

int main() {
    cout << mult(5, sum);
    return 0;
}

What you are doing now is passing the result of the sum call in main, and that result is an integer and not a function.

Upvotes: 1

Mike Woolf
Mike Woolf

Reputation: 1210

You're not passing the function as a parameter. You are passing the return value of the function. Change mult's second parameter to be an int.

Upvotes: 0

Related Questions