如何在函数指针中包含参数?

时间:2015-03-11 09:19:32

标签: c++ function-pointers

如何在函数指针中包含参数?

此代码创建一个可以添加两个整数的函数指针:

int addInt(int n, int m) {
    return n+m;
}
int (*functionPtr)(int,int);
functionPtr = addInt;
(*functionPtr)(3,5); // = 8

例如,我想创建一个函数指针,其中第一个参数始终为5,因此该函数接受一个int并添加五个。另一个第一个参数是8。

这可以使用addInt吗?类似的东西:

// make-believe code that of course won't work 
int (*functionPtr)(int);
functionPtr = addInt(5);
(*functionPtr)(3); // = 8
(*functionPtr)(9); // = 14

3 个答案:

答案 0 :(得分:4)

像这样使用std::bind

using namespace std::placeholders;
auto f = std::bind(addInt, 5, _1);

f(1); //returns 6

答案 1 :(得分:3)

你真正想要的是一个closure(你可能也想要curryfication,但是C ++没有那个;如果你真的需要,可以考虑切换到Ocaml。)

C+14C++11有闭包(但不是早期版本的C ++)。阅读C ++ lambda functions(或匿名函数)和标准<functional>标题及其std::function模板。

这是给定一些整数d的函数返回d的转换,即函数取整数x并返回x+d

#include <functional>
std::function<int(int)> translation(int d) {
  return [=](int x) { return addInt(x,d) /* or x+d */ ; };
}

请注意,std::function - s 不是只是C函数指针。它们还包含封闭值(d示例中的translation

autodecltype说明符非常有用。 例如:

auto addfive = translation(5);
std::cout << addfive(3) << std::end; // should output 8

答案 2 :(得分:3)

使用std :: bind和占位符

#include <iostream>
#include <functional>

using namespace std;

int addInt(int n, int m) {
    return n+m;
}

int main() {
    int (*functionPtr)(int,int);
    functionPtr = addInt;
    (*functionPtr)(3,5); // = 8
    auto f2 = std::bind( addInt, std::placeholders::_1, 5);
    auto f3 = std::bind( addInt, 8, std::placeholders::_1);
    std::cout << f2(1) << "\n";;
    std::cout << f3(1) << "\n";;
}

输出:
   6
   9