Question

In the following simple code in C++, I introduce a trivial procedure, 'count_out', which takes in a (pointer to a) function f(i), which takes an int argument and returns an int, and evaluates this function at 10 successive points and prints out the results.

Now 'count_out' works fine with a function like 'multiplyby2' which takes an int and returns an int. However, I want to feed the 'count_out' procedure with a function like 'add', which takes in two int's; but in order for 'add' to look like 'int f (int)' function, I specify the second argument (b) as e.g. 10. But how can I make C++ understand this: To take 'add' with the second argument specified, as a function which takes in a single int and returns int, so that I can feed it to 'count_out'?

// C++ code snippet:

#include <iostream>
using namespace std ;

int multiplyby2 (int i) {
    return 2 * i ;
}

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

void count_out( int (*f) (int) ){
    for(int i=1; i<=10; i++) cout << f(i) << endl ;
}

void main() {

  count_out ( &multiplyby2 ) ; // works fine.
  count_out ( &add ( ,10) ) ; // produces compilation errors!
  //note that 'add (int a , 10 )' would be a function which returns a + 10 .

}
Was it helpful?

Solution

A lambda should do the trick:

count_out([](int n) { return add(n, 10); });

Non-capturing lambdas are implicitly convertible to the respective function pointer type.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top