转自 http://www.hankcs.com/program/cpp/c11-std-function-usage.html

function可以将普通函数,lambda表达式和函数对象类统一起来。它们并不是相同的类型,然而通过function模板类,可以转化为相同类型的对象(function对象),从而放入一个map里

在看Cocos2d-x的范例代码时,随处可见“很奇怪”的语法:

static std::function<Layer*()> createFunctions[] =
{
CL(CameraTest1),
//...
};

其中CL是一个宏,对应如下lambda表达式:

  1. #define CL(__className__) [](){ return __className__::create();}

还算好懂,感觉是个工厂模式,同时用宏模拟了接口。

但是这个std::function<Layer*()>却让我少见多怪了,翻开第五版《C++ Primer》,才知道原来是C++11的新特性——可调用对象模板类。一句话说明问题,std::function<Layer*()>代表一个可调用对象,接收0个参数,返回Layer*。

至于function的深入理解,还是用代码说明吧。

#include <iostream>
#include <map>
#include <functional>
using namespace std; // 普通函数
int add(int i, int j) { return i + j; }
// lambda表达式
auto mod = [](int i, int j){return i % j; };
// 函数对象类
struct divide
{
int operator() (int denominator, int divisor)
{
return denominator / divisor;
}
}; ///////////////////////////SubMain//////////////////////////////////
int main(int argc, char *argv[])
{
// 受限的map
map<char, int(*)(int, int)> binops_limit;
binops_limit.insert({ '+', add });
binops_limit.insert({ '%', mod });
// 错误 1 error C2664: “void std::_Tree<std::_Tmap_traits<_Kty,_Ty,_Pr,_Alloc,false>>::insert(std::initializer_list<std::pair<const _Kty,_Ty>>)”: 无法将参数 1 从“initializer-list”转换为“std::pair<const _Kty,_Ty> &&”
// binops_limit.insert({ '%', divide() }); // 更灵活的map
map<char, function<int(int, int)>> binops =
{
{ '+', add },
{ '-', minus<int>() },
{ '*', [](int i, int j){return i - j; } },
{ '/', divide() },
{ '%', mod },
};
cout << binops['+'](, ) << endl;
cout << binops['-'](, ) << endl;
cout << binops['*'](, ) << endl;
cout << binops['/'](, ) << endl;
cout << binops['%'](, ) << endl;
system("pause");
return ;
}
///////////////////////////End Sub//////////////////////////////////

如上所示,function可以将普通函数,lambda表达式和函数对象类统一起来。它们并不是相同的类型,然而通过function模板类,可以转化为相同类型的对象(function对象),从而放入一个map里

另外我实际测试的结果来看,在VS2013编译器下,上述代码可以通过,而第五版《C++ Primer》第512页第一行所言“错误:mod不是一个函数指针”并没有发生错误,有可能是对C++11标准的不同实现吧。

C++11 std::function用法的更多相关文章

  1. C/C++ C++ 11 std::function和std::bind用法

    std::bind() std::bind 主要用于绑定生成目标函数,一般用于生成的回调函数,cocos的回退函数都是通过std::bind和std::function实现的.两个点要明白: 1.绑定 ...

  2. C++ 11 std::function std::bind使用

    cocos new 出新的项目之后,仔细阅读代码,才发现了一句3.0区别于2.0的代码: auto closeItem = MenuItemImage::create( "CloseNorm ...

  3. c++11——std::function和bind绑定器

    c++11中增加了std::function和std::bind,可更加方便的使用标准库,同时也可方便的进行延时求值. 可调用对象 c++中的可调用对象存在以下几类: (1)函数指针 (2)具有ope ...

  4. C++11 std::function、std::bind和lambda表达式

    参考博客: C++可调用对象详解-https://www.cnblogs.com/Philip-Tell-Truth/p/5814213.html 一.关于std::function与std::bin ...

  5. C++11新特性之二——std::bind std::function 高级用法

    /* * File: main.cpp * Author: Vicky.H * Email: eclipser@163.com */ #include <iostream> #includ ...

  6. C++11中的std::function

    看看这段代码 先来看看下面这两行代码: std::function<void(EventKeyboard::KeyCode, Event*)> onKeyPressed; std::fun ...

  7. C++11之std::function和std::bind

    std::function是可调用对象的包装器,它最重要的功能是实现延时调用: #include "stdafx.h" #include<iostream>// std ...

  8. 【转】C++11中的std::function

    原文地址:http://www.jellythink.com/archives/771 看看这段代码 先来看看下面这两行代码: std::function<void(EventKeyboard: ...

  9. 转 C++11之std::function和std::bind

    std::function是可调用对象的包装器,它最重要的功能是实现延时调用: #include "stdafx.h" #include<iostream>// std ...

随机推荐

  1. PLSQL 申明和游标

    --从键盘输入一个数 accept b prompt '请输入一个大于零的数字'; declare anum number := &b; begin loop dbms_output.put_ ...

  2. SQL 的简单命令(增删改查)

    数据库操作的资料: 链接: https://pan.baidu.com/s/1dFl3q6X 密码: nvy7-- 增:insert into 表名 (列名) values (值) ,'dew') - ...

  3. iOS 自定义UITableViewCell

    #import <UIKit/UIKit.h> @interface AppDelegate : UIResponder <UIApplicationDelegate> @pr ...

  4. js markdown chart flow

    http://knsv.github.io/mermaid/#example-of-a-marked-renderer

  5. 【转】用CSS代码写出的各种形状图形的方法

    一共收集整理了图形20个,比较实用,同时也为了熟悉CSS的代码.整合了一下,有错误欢迎指出. 1.正方形 #square {width: 100px;height: 100px;background: ...

  6. contenteditable

    http://www.w3school.com.cn/tags/att_global_contenteditable.asp 做编辑器经常用这个属性 使得整个编辑区域所见所得 http://www.c ...

  7. 在struts里使用Kindeditor注意事项

    struts配置文件里 <filter-mapping>          <filter-name>struts2</filter-name>          ...

  8. Java基础之处理事件——应用程序中的语义事件监听器(Sketcher 5 with element color listeners)

    控制台程序. 为了标识元素的类型,可以为菜单已提供的4中元素定义常量,用作ID.这有助于执行菜单项监听器的操作,还提供了一种标识颜色类型的方式.我们会累积许多应用程序范围的常量,所以把它们定义为可以静 ...

  9. 封装smarty类

    <?php/** * Project:     Smarty: the PHP compiling template engine * File:        Smarty.class.php ...

  10. yii框架中邮箱激活(数字签名)

    控制器: //发送邮箱,激活账号   public function actionEmail()   {        $email=Yii::$app->request->get('em ...