• 一段关于c++11中lambda表达式和std::function的体验代码


     1 #include <iostream>
     2 #include <string>
     3 #include <functional>
     4 
     5 // lambda表达式可以使用std::function封装
     6 std::function<std::string(void)> getLambda1() {
     7     return [](){return "She said: ";};
     8 }
     9 
    10 // 要使用lambda表达式作为参数,需要使用函数模版
    11 template<typename Lambda>
    12 std::function<void(void)> getLambda2(Lambda l, const std::string& name) {
    13     return [&](){
    14         l(name);
    15         std::cout << "Do you know me?" << std::endl;
    16     };
    17 }
    18 
    19 // 普通函数
    20 void foo() {
    21     std::cout << "I am foo!" << std::endl;
    22 }
    23 
    24 // 成员函数
    25 class CFoo {
    26 public:
    27     virtual void foo() {
    28         std::cout << "I am CFoo::foo!" << std::endl;
    29     }
    30 };
    31 
    32 int main() {
    33     // auto类型可以自动推演出lambda表达式的类型
    34     auto lam1 = [&](const std::string& name) {
    35         std::cout << (getLambda1())() << "I am " << name << ", a lambda expression!" << std::endl;    
    36     };
    37     
    38     lam1("Lucy");
    39     getLambda2(lam1, "Lily")();
    40     
    41     // 在不使用第三方库的情况下,函数指针和成员函数指针终于可以是一个东西了
    42     {
    43         std::function<void()> f = foo;
    44         f();
    45         CFoo bar;
    46         f = std::bind(&CFoo::foo, &bar);
    47         f();
    48     }
    49 }
    50 
    51 //gcc 4.6.2 编译通过
  • 相关阅读:
    shell脚本使用记录一:操作文件
    用IDEA在Tomcat上部署项目
    通过反射获取属性名和属性类型
    IDEA设置生成类基本注释信息
    有序的Map集合--LinkedHashMap
    书面格式注意的问题
    悲观锁和乐观锁的区别
    解析xml文件的四种方式
    jsp的四种范围
    jsp的两种跳转方式和区别
  • 原文地址:https://www.cnblogs.com/legendlee/p/2730369.html
Copyright © 2020-2023  润新知