在下面的 C++ 简单代码中,我介绍了一个简单的过程“count_out”,它接受一个(指向 a 的)函数 f(i),它接受一个 int 参数并返回一个 int,并计算这个函数在 10 个连续的点并打印出结果。
现在 'count_out' 可以很好地与像 'multiplyby2' 这样接受一个 int 并返回一个 int 的函数一起工作。 但是,我想为“count_out”过程提供一个像“add”这样的函数,它接受两个 int;但是为了让“add”看起来像“int f (int)”函数,我将第二个参数 (b) 指定为例如10. 但是我怎样才能让 C++ 理解这一点:将“add”与指定的第二个参数作为一个函数,它接受一个 int 并返回 int,以便我可以将它提供给“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 .
}
最佳答案
lambda 应该可以解决问题:
count_out([](int n) { return add(n, 10); });
非捕获 lambda 可以隐式转换为相应的函数指针类型。
关于c++ - 在指定一些(不是全部)参数时传递指向函数的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22785803/