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

How to include arguments in a function pointer?

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

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

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

例如,我想制作一个第一个参数始终为 5 的函数指针,以便该函数接受一个 int 并添加 5。另一个第一个参数是 8.

这可以使用 addInt 吗?类似于:

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

像这样使用std::bind

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

f(1); //returns 6

您真正想要的是 closure(您可能还需要 curryfication,但 C++ 没有;如果您真的需要,请考虑切换到 Ocaml)。

C+14 and C++11 have closures (but not earlier versions of C++). Read about C++ lambda functions (or anonymous functions) and the standard <functional> header and its std::function 模板。

这是一个函数,它给出了一些整数 d returns 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 示例中)

auto and decltype 说明符非常有用。 例如:

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

使用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