加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

lambda – 如何在C 0x中重载运算符以组合函数?

发布时间:2020-12-16 03:37:05 所属栏目:百科 来源:网络整理
导读:有没有办法超载,比如运算符的功能组合?运算符应该在lambda和std :: function上无缝地工作? 要求: 解决方案不应包含嵌套绑定调用, 左操作数可以是具有任意数量参数的函数类型,和 不应创建多个函数对象实例. 这是一个快速而肮脏的示例,说明了所需的行为: #
有没有办法超载,比如>>运算符的功能组合?运算符应该在lambda和std :: function上无缝地工作?

要求:

>解决方案不应包含嵌套绑定调用,
>左操作数可以是具有任意数量参数的函数类型,和
>不应创建多个函数对象实例.

这是一个快速而肮脏的示例,说明了所需的行为:

#include <iostream>
#include <functional>

using namespace std;

// An example of a quick and dirty function composition.
// Note that instead of 'std::function' this operator should accept
// any functional/callable type (just like 'bind').
template<typename R1,typename R2,typename... ArgTypes1>
function<R2(ArgTypes1...)> operator >> (
                const function<R1(ArgTypes1...)>& f1,const function<R2(R1)>& f2) {
    return [=](ArgTypes1... args){ return f2(f1(args...)); };
}

int main(int argc,char **args) {
    auto l1 = [](int i,int j) {return i + j;};
    auto l2 = [](int i) {return i * i;};

    function<int(int,int)> f1 = l1;
    function<int(int)> f2 = l2;

    cout << "Function composition: " << (f1 >> f2)(3,5) << endl;

    // The following is desired,but it doesn't compile as it is:
    cout << "Function composition: " << (l1 >> l2)(3,5) << endl;

    return 0;
}

解决方法

(l1>> l2)永远不会工作.

它们是由编译器生成的函数对象,不包含该运算符,因此除非您计划将编译器修改为不符合,否则它将始终如此.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读