将双变量std ::函数转换为单变量 [英] Transforming a two-variable std::function to a single-variable one

查看:186
本文介绍了将双变量std ::函数转换为单变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,它获取两个值x和y,并返回结果:

I have a function which gets two values, x and y, and returns the result:

std::function< double( double, double ) > mult = 
  []( double x, double y){ return x*y; };

现在我想为常数y得到单变量函数。我写了以下代码,但它不工作。

Now I want to get a single-variable function for a constant y. I have written the following code, but it doesn't work.

std::function<
  std::function< double(double) > (
    std::function< double(double, double) >,
    double
  )
> funcYgivenX =
  [](std::function< double(double, double) > func2d, double inX) {
    return [&func2d, &inX]( double inY ) {
      return func2d(inX, inY);
    };
  };

我在这里做错了什么?

What am I doing wrong here? And what is the best (most efficient) way to do this?

推荐答案

在C ++ 11中 std :: bind 本质上已经过时,引入了lambdas。
下面是使用lambda绑定的例子。

In C++11 std::bind is essentially obsolete with introduction of lambdas. Here's an example of binding using a lambda.

int add(int a, int b) {return a + b;}

int main() {
  auto add2 = [](int a){ return add(a,2); };

  return 0;
}

关于lambda的优先选择 std ::绑定可以阅读Scott Meyers的第32项 Effective Modern C ++ 。在C ++ 11中,不可能使用lambda移动捕获,并且此行为只能被模拟与 std :: bind 。在C ++ 14中引入了lambdas的init捕获,即使这种情况也可以很好地用lambdas解决。

For reference concerning preference of lambdas over std::bind one can read Effective Modern C++ by Scott Meyers, Item 32. In C++11 it's not possible to move capture with a lambda, and this behavior can only be emulated with std::bind. With introduction of init capture for lambdas in C++14, even that corner case can be nicely solved with lambdas.

这篇关于将双变量std ::函数转换为单变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆