首页 > 解决方案 > 在 C++ 中不使用 lambda 的函数组合

问题描述

我想知道如何转换函数组合,但不使用 lambda。以下是来自https://stackoverflow.com/a/50035197的原始代码。

template<class Root, class... Branches> auto comp(Root &&root, Branches &&... branches) {
 return [root, branches...](auto &&...args) {
     return root(branches(std::forward<decltype(args)>(args)...)...);
 };
}
int f(int x, int y) { return x + y; }
int g(int x) { return x * 19; }
int h(int x) { return x + 2; }

#include <iostream>
int main() {
        auto fgh = comp(f, g, h);
        std::cout << fgh(2) << '\n';
}

我试图在comp不使用 lambda 的情况下模拟该函数,但编译失败:

template<class Root, class... Branches>
class compose2  {
  Root root; 
  tuple<Branches...> branches;
  public:
  compose2(Root r, Branches... br) : root(r), branches(br...) {};
  template <class... Args> 
    decltype(auto) operator()(Args... args) {
      return root(branches((args)...)...); // compile error, because a tuple is not a parameter pack
    }   
}; 

我知道参数包不能是成员变量,所以我的第一个想法是使用元组来存储仿函数(branches),但我被困在这里。branches所以问题是,如何扩展comp

标签: c++

解决方案


推荐阅读