在C ++ 11中是否可以将功能组合为新功能? [英] Is it possible in C++11 to combine functions into a new function?

查看:72
本文介绍了在C ++ 11中是否可以将功能组合为新功能?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这更多是一种理论上的问题.在C ++ 11中是否可以将功能组合为新功能?例如:

This is more a kind of theoretical question. Is it possible in C++11 to combine functions into a new function? For example :

auto f = [](int i){return i * 2;};
auto g = [](int i){return i + 10;};

这可行:

auto c = f(g(20)); // = 60

但是我想要一个存储组合的对象,例如

But I want an object that stores the combination, like

auto c = f(g);
std::cout << c(20) << std::endl; //prints 60

修改: 另外,我要创建的是函数a,您可以给它一个函数b和一个int n,并返回给定函数b的第n个组合.例如(不可编译)

Additionally what i want to create is a function a, which you can give a function b and an int n, and which returns the n'th combination of the given function b. For example (not compilable)

template<typename T>
auto combine(T b, int i) -> decltype(T)
{
   if (i == 0)
      return b;

   return combine(b, i - 1);      
}

auto c = combine(f, 2); //c = f(f(f(int)))

推荐答案

您可以按照以下方式编写内容:

You can write something along the lines of:

#include <functional>
#include <iostream>

template<class F>
F compose(F f, F g)
{
  return [=](int x) { return f(g(x)); };
}

int main()
{
  std::function<int (int)> f = [](int i) { return i * 2; };
  std::function<int (int)> g = [](int i) { return i + 10; };

  auto c = compose(f, g);
  std::cout << c(20) << '\n';  // prints 60
}

可以简单地将代码扩展为涵盖问题的后半部分:

The code can be simply extended to cover the second half of the question:

template<class F>
F compose(F f, unsigned n)
{
  auto g = f;

  for (unsigned i = 0; i < n; ++i)
    g = compose(g, f);

  return g;
}

int main()
{
  std::function<int (int)> h = [](int i) { return i * i; };

  auto d = compose(h, 1);
  auto e = compose(h, 2);
  std::cout << d(3) << "\n"    // prints 81
            << e(3) << "\n";   // prints 6561
}

注意.在这里使用std::function.它不是lambda,而是以性能成本包装lambda.

NOTE. Here using std::function. It isn't a lambda but wraps a lambda with a performance cost.

这篇关于在C ++ 11中是否可以将功能组合为新功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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