转自 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. [Slimdx]顶点和索引缓冲,绘制了2个分离的三角形

    定义网格顶点和索引缓冲,绘制了2个分离的三角形. using System; using System.Drawing; using RGeos.SlimScene.Core; using SlimD ...

  2. js获取页面及个元素高度、宽度

    网页可见区域宽: document.body.clientWidth; 网页可见区域高: document.body.clientHeight; 网页可见区域宽: document.body.offs ...

  3. Linux-QT 开发环境搭建以及编译镜像

    搭建Linux-QT 开发环境,需要先搭建Android 的编译环境,然后在Android 编译环境的基础上,再搭建Linux-QT 编译环境. 第一:编译器. 第二:设置环境变量.环境变量设置后,编 ...

  4. The Struts dispatcher cannot be found. This is usually caused by using Strut

    The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the assoc ...

  5. python入门到精通[一]:搭建开发环境

    摘要:Python认识,及在windows和linux上安装环境,测试是否安装成功. 1.写在前面 参加工作也有5年多了,一直在做.net开发,近一年有做NodeJS开发.从一开始的不习惯,到逐步适应 ...

  6. HTML部分标签和代码

    1.1.1 一般标签.格式控制标签 所谓HTML就是 Hyper Text Markup Language(超无文本标记语言) <html>   开始标签 <head> 网页上 ...

  7. html 标签内部元素上下居中

    <div style="width: 200px; height: 200px; border: 1px solid red; line-height: 200px;"> ...

  8. yii添加行的增删改查

    效果图: 控制器: <?phpnamespace backend\controllers;use Yii;use yii\web\Controller;use backend\models\Zh ...

  9. ef 5 在 DropCreateDatabaseAlways 报错,the connection is currently used

    go sp_who2 -- db_id 数据库名称,查询出来的结果执行一遍就能关闭所有连接 SELECT N'kill '+ CAST(spid AS varchar) FROM master..sy ...

  10. kafka迁移数据目录

    问题 先前存储kafka日志的磁盘空间太小,zabbix警报不断,于是加了磁盘,将日志存到新磁盘上. 解决方案 依次在每台机器上操作,保证有机器能响应producer和consumer的操作. 加磁盘 ...