一生一世学坛

 找回密码
 立即注册
搜索
查看: 4302|回复: 0
打印 上一主题 下一主题

匿名函数作为参数传递

[复制链接]

334

主题

385

帖子

6830

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
6830
跳转到指定楼层
楼主
发表于 2022-1-27 16:00:45 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
方法一:
#include <iostream>
#include <functional>
#include <string>

void print(std::function<std::string ()> const &f){
    std::cout<<f()<<std::endl;
}

int main() {
    std::cout << "Hello, World!" << std::endl;

    int num = 101;
    auto a = [&]//以引用的方式捕获本函数中的变量
             () //无参数
             ->std::string {//返回值的类型为std::string
        return std::to_string(num);
    };
    print(a);
    num++;
    print(a);

    return 0;
}


例子2:
#include <iostream>
#include <thread>
#include <chrono>
#include <vector>
#include <atomic>

int main() {

    std::atomic_uint num(0);//atomic_uint时原子操作类,在不同的线程中访问时,是线程安全的。
    // 无参数lambda表达式
    auto a = [&]() -> void {
        std::this_thread::sleep_for(std::chrono::milliseconds(num*20));//休眠i*2ms
        num += 100;
    };
    // 新建子线程
    std::thread t(a);
    t.join();
    int value = num;
    printf("%d\n",value);

    // 有参数lambda表达式
    auto b = [&](int i) -> void {
        std::this_thread::sleep_for(std::chrono::milliseconds(i));//休眠i*2ms
        num += i;
    };
    // 新建子线程
    std::thread tt(b,1000);
    tt.join();

    value = num;
    printf("%d\n",value);


    return 0;
}


方法二:
#include <iostream>
#include <string>

template <typename F>
void print(F const &f){
    std::cout<<f()<<std::endl;
}

int main() {
    std::cout << "Hello, World!" << std::endl;

    int num = 101;
    auto a = [&]//以引用的方式捕获本函数中的变量
             () //无参数
             ->std::string {//返回值的类型为std::string
        return std::to_string(num);
    };
    print(a);
    num++;
    print(a);

    return 0;
}

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

QQ|Archiver|手机版|小黑屋|分享学习  

GMT+8, 2024-5-17 14:19 , Processed in 0.046371 second(s), 6 queries , File On.

声明:本站严禁任何人以任何形式发表违法言论!

本站内容由网友原创或转载,如果侵犯了您的合法权益,请及时联系处理!© 2017 zamxqun@163.com

皖公网安备 34010402700634号

皖ICP备17017002号-1

快速回复 返回顶部 返回列表