使用结构参数化函数

Parameterizing a function using a struct

下面的代码无法编译。函数foo接受一个函数指针f作为参数,f严格接受一个int作为参数,returns一个int。在此示例中,foo 始终使用参数 3 调用 f。我想将一个函数传递给 foo 以便在评估 f(3) 时,它会与其他一些参数一起评估;但是,我不能将带有 2 个整数的函数作为参数传递给 foo(这个问题是对真实问题的类比)。

#include <iostream>

void foo(int(*f)(int))
{
  std::cout << f(3) << std::endl;
}

struct plusX
{
  plusX(int x_) : x(x_) {}
  int x;
  int plus(int y)
  {
    return x + y;
  }
};

int main()
{
  plusX px4(4);
  foo(&px4.plus);  // ERROR!
}

ISO C++ forbids taking the address of a bound member function to form a pointer to member function. Say '&plusX::plus'

两种解决方案。如果现有代码使用函数,第一个解决方案不需要重构代码。

1) 使用仿函数:

#include <iostream>

template<typename F>
void foo(F&& f)
{
  std::cout << f(3) << std::endl;
}

struct my_functor
{
  my_functor(int x_) : x(x_) {}
  int operator()(int y)
  {
    return x + y;
  }
  int x;
};

int main()
{
  my_functor f(4);
  foo(f);
}

2) 使用 std::function 和 std::bind

#include <iostream>
#include <functional>

void foo(const std::function<int(int)>& f)
{
  std::cout << f(3) << std::endl;
}

int add(int x, int y)
{
  return x + y;
}

int main()
{
  std::function<int(int)> f_binded = std::bind(add, 4, std::placeholders::_1);
  foo(f_binded);
}