【问题标题】:How to make a pointer to a function and define some arguments to this function in C++如何在 C++ 中创建指向函数的指针并为该函数定义一些参数
【发布时间】:2021-09-08 22:21:08
【问题描述】:

我想做这样的事情:

int a(int a, int b)
{
    return 0;
}

int main()
{
    int n = 2;
    int (*b)(int) = a(a = n);
    return 0;
}

我想实现它,因为我希望能够将一个函数作为参数传递给另一个函数,但定义了一些值。

我怎样才能实现它?

【问题讨论】:

  • int (*b)(int) = [](int b) { return a(2, b); };
  • 顺便说一句,您应该使用不同的描述性名称。
  • @IgorTandetnik 谢谢,但如果我想捕获一个变量,它就不起作用。诠释 n = 2; int (*b)(int) = [n](int b) { return a(n, b); };
  • 在这种情况下,让它auto b = ...; 它不再是一个普通的函数指针(它不可能,因为简单的实际原因,普通函数指针中也没有空格存储捕获的值)。

标签: c++ function pointers arguments function-pointers


【解决方案1】:

假设你的另一个函数是这样的:

using func_ptr_t = int(*)(int);

void other_func(func_ptr_t f) {
    f(3);
}

然后您可以使用lambda expression 来绑定其中一个参数:

int foo(int a, int b) // dont use same name for function and its argument
{
    return 0;
}

int main() {
    auto f = [](int b){ return foo(2,b); };
    other_func(f);
}

如果要捕获要绑定的参数,则不能将 lambda 转换为函数指针。函数没有状态。一种选择是将other_func 设为模板:

template <typename F>
void other_func(F f) { f(3); }
int foo(int a, int b) { return 0; }

int main() {
    int n = 2;
    auto f = [n](int b){ return foo(n,b); };
    other_func(f);
}

然而,现在other_func 的不同实例是不同的函数。有时这是不希望的,那么您需要某种形式的类型擦除,例如通过std::function&lt;int(int)&gt;

【讨论】:

  • other_func() 不需要成为此示例工作的模板,例如:void other_func(int (*f)(int)) { f(3); } 当 OP 询问一件特定的事情时,我们不要通过将多种语言功能混合在一起来混淆问题。
  • @RemyLebau 不需要,但它也不会受到伤害。好吧,也许确实如此。要看。添加了非模板版本
  • @RemyLebeau “让我们一次专注于一种语言功能”完全同意
  • 我会说模板版本要好得多,因为它更通用。使用函数指针版本,您不能传递x 而不是2(其中x 是一些局部变量)。
  • 如果我捕获了一个值,它就不起作用。诠释 n = 3; int (*p)(int) = [n](int b){ return foo(n,b); };
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-12
  • 2011-02-21
  • 1970-01-01
  • 2011-07-11
  • 2014-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多