C++ 中的通用多功能函数组合/流水线

如何解决C++ 中的通用多功能函数组合/流水线

是否可以在 C++ 20 中实现通用的多函子组合/流水线?

struct F{//1st multi-functor
  template<typename T> void operator()(const T& t){/*...*/}
};
struct G{//2nd multi-functor
  template<typename T> void operator()(const T& t){/*...*/}
};

F f;
G g;
auto pipe = f | g;//what magic should happen here to achieve g(f(...)) ? how exactly to overload the operator|()?

pipe(123);   //=> g(f(123);
pipe("text");//=> g(f("text");

编辑: 我尝试了这两个建议(来自@Some_programmer_dude 和@Jarod42),但我在错误中迷失了:

  1. 建议像@Some_programmer_dude 一样重载运算符|()
template<class Inp,class Out>
auto operator|(Inp inp,Out out){
    return [inp,out](const Inp& arg){
        out(inp(arg));
    };
}

生成:

2>main.cpp(71,13): error C3848: expression having type 'const Inp' would lose some const-volatile qualifiers in order to call 'void F::operator ()<F>(const T &)'
2>        with
2>        [
2>            Inp=F
2>        ]
2>        and
2>        [
2>            T=F
2>        ]
  1. 直接使用 lambda 而不是像 @Jarod42 建议的那样重载 operator|():
auto pipe = [=](const auto& arg){g(f(arg));};

生成:

2>main.cpp(86,52): error C3848: expression having type 'const F' would lose some const-volatile qualifiers in order to call 'void F::operator ()<_T1>(const T &)'
2>        with
2>        [
2>            _T1=int,2>            T=int
2>        ]

解决方法

你快到了

template<class Inp,class Out>
auto operator|(Inp inp,Out out){
    return [inp,out](const Inp& arg){
        out(inp(arg));
    };
}

struct F{//1st multi-functor
  template<typename T> void operator()(const T& t){/*...*/}
};
struct G{//2nd multi-functor
  template<typename T> void operator()(const T& t){/*...*/}
};

F f;
G g;
auto pipe = f | g;

但是,您忽略了一些细微差别。

首先,lambda 中的 outinpconst,因为闭包类型有一个 const 限定的 operator()。另外,lambda 的参数类型应该是 auto,而不是 Inp,否则你只能pipe(f)

您想为某个 g(f(x)) 调用 x,但 f 的返回类型是 void,这需要其他内容。

您提供的 | 与算术 | 会产生歧义。

struct some_type {};

template<typename F>
concept unary_invocable = std::invocable<F,some_type>;

template <unary_invocable Inp,unary_invocable Out>
auto operator|(Inp inp,out](auto&& arg){
        return out(inp(std::forward<decltype(arg)>(arg)));
    };
}

struct F{//1st multi-functor
  template<typename T> auto operator()(const T& t) const {/*... return something*/}
};
struct G{//2nd multi-functor
  template<typename T> auto operator()(const T& t) const {/*... return something*/}
};
,

这里有一个快速的小图书馆。

#define RETURNS(...) \
  noexcept(noexcept(__VA_ARGS__)) \
  -> decltype(__VA_ARGS__) \
  { return __VA_ARGS__; }

namespace ops {
  template<class D>
  struct op_tag;

  template<class Second,class First>
  struct pipe_t;

  template<class D>
  struct op_tag {
    D const& self() const { return *static_cast<D const*>(this); }
    D& self() { return *static_cast<D*>(this); }

    auto operator()(auto&&...args) const
      RETURNS( self()(decltype(args)(args)...) )
    auto operator()(auto&&...args)
      RETURNS( self()(decltype(args)(args)...) )
  };
  
  template<class Second,class First>
  struct pipe_t:op_tag<pipe_t<Second,First>> {
    Second second;
    First first;
    pipe_t( Second second_,First first_ ):
      second(std::move(second_)),first(std::move(first_))
    {}
    auto operator()(auto&&...args)
      RETURNS( second(first(decltype(args)(args)...)) )
    auto operator()(auto&&...args) const
      RETURNS( second(first(decltype(args)(args)...)) )
  };
  template<class Second,class First>
  auto operator|(op_tag<First> const& first,op_tag<Second> const& second)
    RETURNS( pipe_t<Second,First>{ second.self(),first.self() } )
}

以贪婪的方式重载运算符被认为是粗鲁的。您只希望您的运算符重载参与您特别支持的类型。

这里我要求类型继承自 op_tag<T> 以表明它们有兴趣成为一个操作。

然后我们稍微修改您的代码:

struct F:ops::op_tag<F>{//1st multi-functor
  template<typename T>
  auto operator()(const T& t){
      std::cout << "f(" << t << ")";
      return -1;
  }
};
struct G:ops::op_tag<G>{//2nd multi-functor
  template<typename T> auto operator()(const T& t){
      std::cout << "g(" << t << ")";
      return 7;
  }
};

添加标签和返回值(否则,f(g(x)) 没有意义,除非 g 返回一些东西)。

你写的代码现在可以工作了。

如果您愿意,我们还可以添加对 std::function 甚至原始函数的支持。您可以在 operator| 中添加合适的 namespace ops 重载,并要求人们 using ops::operator| 将运算符带入范围(或将其与 op_tag 类型一起使用)。

Live example

输出:

f(123)g(-1)f(text)g(-1)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res