<functional> 系列

目录

前言

一、std::function的原理与接口

  1.1 std::function是函数包装器

  1.2 C++注重运行时效率

  1.3 用函数指针实现多态

  1.4 std::function的接口

二、std::function的实现

2.1 类型系统

2.1.1 异常类

2.1.2 数据存储

2.1.3 辅助类

2.1.4 内存管理基类

2.1.5 仿函数调用

2.1.6 接口定义

2.1.7 类型关系

2.2 方法的功能与实现

2.2.1 多态性的体现

2.2.2 本地函数对象

2.2.3 heap函数对象

2.2.4 两种存储结构如何统一

2.2.5 根据形式区分仿函数类型

2.2.6 实现组装成接口

后记

附录

前言

为什么要剖析 std::function 呢?因为笔者最近在做一个 std::function 向单片机系统的移植与扩展。

后续还会有 std::bind 等标准库其他部分的移植。

一、std::function的原理与接口

1.1 std::function是函数包装器

std::function ,能存储任何符合模板参数的函数对象。换句话说,这些拥有一致参数类型、相同返回值类型(其实不必完全相同)的函数对象,可以由 std::function 统一包装起来。函数对象的大小是任意的、不能确定的,而C++中的类型都是固定大小的,那么,如何在一个固定大小的类型中存储任意大小的对象呢?

实际上问题还不止存储那么简单。存储了函数对象,必定是要在某一时刻调用;函数对象不是在创建的时候调用,这个特性成为延迟调用;函数对象也是对象,需要处理好构造、拷贝、移动、析构等问题——这些也需要延迟调用,但总不能再用 std::function 来解决吧?

既然 std::function 能存储不同类型的函数对象,可以说它具有多态性。C++中体现多态性的主要是虚函数,继承与多态这一套体制是可以解决这个问题的。相关资料[1] [2]中的实现利用了继承与多态,相当简洁。

1.2 C++注重运行时效率

利用继承与多态,我们可以让编译器帮我们搞定函数对象的析构。就这种实现而言,这是简洁而有效的方法。然而这种实现需要动态内存,在一些情况下不划算,甚至完全没有必要。C++11引入了lambda表达式,其本质也是函数对象。这个对象有多大呢?取决于捕获列表。你写lambda会捕获多少东西?很多情况下就只是一对方括号而已吧。在这种情况下,lambda表达式的对象大小只有1字节(因为不能是0字节),你却为了这没有内容的1字节要调用动态内存的函数?C++注重运行时效率,这种浪费是不能接受的。

如何避免这种浪费呢?你也许会说我检查传入的对象是不是1字节的空类型。且不论这个trait怎么实现,函数指针、捕获一个int的lambda等类型都声称自己是trivial的小对象,也不应该分配到heap中去。

之前说过,std::function 的大小是固定的,但是这个大小是可以自己定的。我们可以在 std::function 的类定义中加入一个空白的、大小适中的field,用在存放这些小对象,从而避免这些情况下的动态内存操作。同时,既然有了这片空间,也就不需要看传入的对象是不是1字节的空类型了。

而对于更大的类型,虽然这个field不足以存放函数对象,但足以存放一个指针,这种分时复用的结构可以用union来实现。这种小对象直接存储、大对象在heap上开辟空间并存储指针的方法,称为small object optimization。

在利用继承的实现中,函数对象被包装在一个子类中,std::function 中持有一个其父类的指针。然而为了效率,我们需要把空白field和这个指针union起来。union总给人一种底层的感觉,在不确定这个union到底存储的是什么的时候,当然不能通过其中的指针去调用虚函数。在这样的设计中,多态性不再能用继承体系实现了,我们需要另一种实现多态的方法。

1.3 用函数指针实现多态

回想一下虚函数是如何实现的?带有virtual function的类的对象中会安插vptr,这个指针指向一个vtable,这个vtable含有多个slot,里面含有指向type_info对象的指针与函数指针——对,我们需要函数指针!不知你有没有在C中实现过多态,在没有语言特性的帮助下,比较方便的方法是在struct中直接放函数指针。如果要像C++那样用上vptr和vtable,你得管理好每个类及其对应vtable的内容。你以为这种情况在C++中就有所好转吗?只有你用C++的继承体系,编译器才会帮你做这些事。想要自己建立一个从类型到vptr的映射,恐怕你得改编译器了。(更正:C++14引入了变量模板,请移步C++值多态:传统多态与类型擦除之间。)

vptr与vtable的意义是什么?其一,每个基类只对应一个vptr,大小固定,多重继承下便于管理,但这点与这篇文章的主题没有关联;其二,当基类有多个虚函数的时候,使用vptr可以节省存储对象的空间,而如果用函数指针的话,虽然少了一次寻址,但继承带来的空间overhead取决于虚函数的数量,由于至少一个,函数指针的占用的空间不会少于vptr,在虚函数数量较多的情况下,函数指针就要占用比较大的空间了。

既然我们已经无法在 std::function 中使用vptr,我们也应该尽可能减少函数指针的数量,而这又取决于这些函数的功能,进一步取决于 std::function 类的接口。

1.4 std::function的接口

虽然C++标准规定了 std::function 的接口就应该是这样,我还是想说说它为什么应该是这样。关于其他的一些问题,比如保存值还是保存引用等,可以参考相关资料[4]

最基本的,std::function 是一个模板类,模板参数是一个类型(注意是一个类型,不是好几个类型)。我们可以这么写:

  1. std::function<int(double)> f;

f 是一个可调用对象,参数为 double,返回值为 int 。你也许会问,这里既规定了参数类型又规定了返回值类型,怎么就成了一个类型呢?确实是一个类型,int(double) 是一个函数类型(注意不是函数指针)。

std::function 要包装所有合适类型的对象,就必须有对应的构造函数,所以这是个模板构造函数。参数不是通用引用而是直接传值

  1. template <typename F>
  2. function(F);

可能是为了让编译器对空对象进行优化。同样还有一个模板赋值函数,参数是通用引用。

每个构造函数都有一个添加了 std::allocator_arg_t 作为第一个参数、内存分配器对象作为第二个参数的版本,C++17中已经移除(GCC从未提供,可能是因为 std::function 的内存分配无法自定义)。同样删除的还有 assign ,也是与内存分配器相关的。

另外有一个以 std::reference_wrapper 作为参数的赋值函数:

  1. template <typename F>
  2. function& operator=(std::reference_wrapper<F>) noexcept;

可以理解为模板赋值函数的特化。没有相应的构造函数。

默认构造函数、nullptr_t 构造函数、nullptr_t 拷贝赋值函数都将 std::function 对象置空。当 std::function 对象没有保存任何函数对象时, operator bool() 返回 false ,与 nullptr_t 调用 operator== 会返回 true ,如果调用将抛出 std::bad_function_call 异常。

虽然 std::function 将函数对象包装了起来,但用户还是可以获得原始对象的。target_type() 返回函数对象的 typeid ,target() 模板函数当模板参数与函数对象类型相同时返回其指针,否则返回空指针。

作为函数包装器,std::function 也是函数对象,可以通过 operator() 调用,参数按照模板参数中声明的类型传递。

还有一些接口与大部分STL设施相似,有Rule of Five规定的5个方法、 swap() ,以及 std::swap() 的特化等。可别小看这个 swap() ,它有大用处。

总之,函数对象的复制、移动、赋值、交换等操作都是需要的。对客户来说,除了两个 std::function 的相等性判定(笔者最近在尝试实现这个)以外,其他能想到的方法它都有。

二、std::function的实现

std::function 的实现位于 <functional> ,后续版本迁移至了 <bits/std_function.h> 。下面这段代码是GCC 4.8.1(第一个支持完整C++11的版本)中的 <functional> 头文件,共2579行,默认折叠,慎入。

  1. // <functional> -*- C++ -*-
  2.  
  3. // Copyright (C) 2001-2013 Free Software Foundation, Inc.
  4. //
  5. // This file is part of the GNU ISO C++ Library. This library is free
  6. // software; you can redistribute it and/or modify it under the
  7. // terms of the GNU General Public License as published by the
  8. // Free Software Foundation; either version 3, or (at your option)
  9. // any later version.
  10.  
  11. // This library is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15.  
  16. // Under Section 7 of GPL version 3, you are granted additional
  17. // permissions described in the GCC Runtime Library Exception, version
  18. // 3.1, as published by the Free Software Foundation.
  19.  
  20. // You should have received a copy of the GNU General Public License and
  21. // a copy of the GCC Runtime Library Exception along with this program;
  22. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  23. // <http://www.gnu.org/licenses/>.
  24.  
  25. /*
  26. * Copyright (c) 1997
  27. * Silicon Graphics Computer Systems, Inc.
  28. *
  29. * Permission to use, copy, modify, distribute and sell this software
  30. * and its documentation for any purpose is hereby granted without fee,
  31. * provided that the above copyright notice appear in all copies and
  32. * that both that copyright notice and this permission notice appear
  33. * in supporting documentation. Silicon Graphics makes no
  34. * representations about the suitability of this software for any
  35. * purpose. It is provided "as is" without express or implied warranty.
  36. *
  37. */
  38.  
  39. /** @file include/functional
  40. * This is a Standard C++ Library header.
  41. */
  42.  
  43. #ifndef _GLIBCXX_FUNCTIONAL
  44. #define _GLIBCXX_FUNCTIONAL 1
  45.  
  46. #pragma GCC system_header
  47.  
  48. #include <bits/c++config.h>
  49. #include <bits/stl_function.h>
  50.  
  51. #if __cplusplus >= 201103L
  52.  
  53. #include <typeinfo>
  54. #include <new>
  55. #include <tuple>
  56. #include <type_traits>
  57. #include <bits/functexcept.h>
  58. #include <bits/functional_hash.h>
  59.  
  60. namespace std _GLIBCXX_VISIBILITY(default)
  61. {
  62. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  63.  
  64. template<typename _MemberPointer>
  65. class _Mem_fn;
  66. template<typename _Tp, typename _Class>
  67. _Mem_fn<_Tp _Class::*>
  68. mem_fn(_Tp _Class::*) noexcept;
  69.  
  70. _GLIBCXX_HAS_NESTED_TYPE(result_type)
  71.  
  72. /// If we have found a result_type, extract it.
  73. template<bool _Has_result_type, typename _Functor>
  74. struct _Maybe_get_result_type
  75. { };
  76.  
  77. template<typename _Functor>
  78. struct _Maybe_get_result_type<true, _Functor>
  79. { typedef typename _Functor::result_type result_type; };
  80.  
  81. /**
  82. * Base class for any function object that has a weak result type, as
  83. * defined in 3.3/3 of TR1.
  84. */
  85. template<typename _Functor>
  86. struct _Weak_result_type_impl
  87. : _Maybe_get_result_type<__has_result_type<_Functor>::value, _Functor>
  88. { };
  89.  
  90. /// Retrieve the result type for a function type.
  91. template<typename _Res, typename... _ArgTypes>
  92. struct _Weak_result_type_impl<_Res(_ArgTypes...)>
  93. { typedef _Res result_type; };
  94.  
  95. template<typename _Res, typename... _ArgTypes>
  96. struct _Weak_result_type_impl<_Res(_ArgTypes......)>
  97. { typedef _Res result_type; };
  98.  
  99. template<typename _Res, typename... _ArgTypes>
  100. struct _Weak_result_type_impl<_Res(_ArgTypes...) const>
  101. { typedef _Res result_type; };
  102.  
  103. template<typename _Res, typename... _ArgTypes>
  104. struct _Weak_result_type_impl<_Res(_ArgTypes......) const>
  105. { typedef _Res result_type; };
  106.  
  107. template<typename _Res, typename... _ArgTypes>
  108. struct _Weak_result_type_impl<_Res(_ArgTypes...) volatile>
  109. { typedef _Res result_type; };
  110.  
  111. template<typename _Res, typename... _ArgTypes>
  112. struct _Weak_result_type_impl<_Res(_ArgTypes......) volatile>
  113. { typedef _Res result_type; };
  114.  
  115. template<typename _Res, typename... _ArgTypes>
  116. struct _Weak_result_type_impl<_Res(_ArgTypes...) const volatile>
  117. { typedef _Res result_type; };
  118.  
  119. template<typename _Res, typename... _ArgTypes>
  120. struct _Weak_result_type_impl<_Res(_ArgTypes......) const volatile>
  121. { typedef _Res result_type; };
  122.  
  123. /// Retrieve the result type for a function reference.
  124. template<typename _Res, typename... _ArgTypes>
  125. struct _Weak_result_type_impl<_Res(&)(_ArgTypes...)>
  126. { typedef _Res result_type; };
  127.  
  128. template<typename _Res, typename... _ArgTypes>
  129. struct _Weak_result_type_impl<_Res(&)(_ArgTypes......)>
  130. { typedef _Res result_type; };
  131.  
  132. /// Retrieve the result type for a function pointer.
  133. template<typename _Res, typename... _ArgTypes>
  134. struct _Weak_result_type_impl<_Res(*)(_ArgTypes...)>
  135. { typedef _Res result_type; };
  136.  
  137. template<typename _Res, typename... _ArgTypes>
  138. struct _Weak_result_type_impl<_Res(*)(_ArgTypes......)>
  139. { typedef _Res result_type; };
  140.  
  141. /// Retrieve result type for a member function pointer.
  142. template<typename _Res, typename _Class, typename... _ArgTypes>
  143. struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes...)>
  144. { typedef _Res result_type; };
  145.  
  146. template<typename _Res, typename _Class, typename... _ArgTypes>
  147. struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes......)>
  148. { typedef _Res result_type; };
  149.  
  150. /// Retrieve result type for a const member function pointer.
  151. template<typename _Res, typename _Class, typename... _ArgTypes>
  152. struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes...) const>
  153. { typedef _Res result_type; };
  154.  
  155. template<typename _Res, typename _Class, typename... _ArgTypes>
  156. struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes......) const>
  157. { typedef _Res result_type; };
  158.  
  159. /// Retrieve result type for a volatile member function pointer.
  160. template<typename _Res, typename _Class, typename... _ArgTypes>
  161. struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes...) volatile>
  162. { typedef _Res result_type; };
  163.  
  164. template<typename _Res, typename _Class, typename... _ArgTypes>
  165. struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes......) volatile>
  166. { typedef _Res result_type; };
  167.  
  168. /// Retrieve result type for a const volatile member function pointer.
  169. template<typename _Res, typename _Class, typename... _ArgTypes>
  170. struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes...)
  171. const volatile>
  172. { typedef _Res result_type; };
  173.  
  174. template<typename _Res, typename _Class, typename... _ArgTypes>
  175. struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes......)
  176. const volatile>
  177. { typedef _Res result_type; };
  178.  
  179. /**
  180. * Strip top-level cv-qualifiers from the function object and let
  181. * _Weak_result_type_impl perform the real work.
  182. */
  183. template<typename _Functor>
  184. struct _Weak_result_type
  185. : _Weak_result_type_impl<typename remove_cv<_Functor>::type>
  186. { };
  187.  
  188. /// Determines if the type _Tp derives from unary_function.
  189. template<typename _Tp>
  190. struct _Derives_from_unary_function : __sfinae_types
  191. {
  192. private:
  193. template<typename _T1, typename _Res>
  194. static __one __test(const volatile unary_function<_T1, _Res>*);
  195.  
  196. // It's tempting to change "..." to const volatile void*, but
  197. // that fails when _Tp is a function type.
  198. static __two __test(...);
  199.  
  200. public:
  201. static const bool value = sizeof(__test((_Tp*))) == ;
  202. };
  203.  
  204. /// Determines if the type _Tp derives from binary_function.
  205. template<typename _Tp>
  206. struct _Derives_from_binary_function : __sfinae_types
  207. {
  208. private:
  209. template<typename _T1, typename _T2, typename _Res>
  210. static __one __test(const volatile binary_function<_T1, _T2, _Res>*);
  211.  
  212. // It's tempting to change "..." to const volatile void*, but
  213. // that fails when _Tp is a function type.
  214. static __two __test(...);
  215.  
  216. public:
  217. static const bool value = sizeof(__test((_Tp*))) == ;
  218. };
  219.  
  220. /**
  221. * Invoke a function object, which may be either a member pointer or a
  222. * function object. The first parameter will tell which.
  223. */
  224. template<typename _Functor, typename... _Args>
  225. inline
  226. typename enable_if<
  227. (!is_member_pointer<_Functor>::value
  228. && !is_function<_Functor>::value
  229. && !is_function<typename remove_pointer<_Functor>::type>::value),
  230. typename result_of<_Functor&(_Args&&...)>::type
  231. >::type
  232. __invoke(_Functor& __f, _Args&&... __args)
  233. {
  234. return __f(std::forward<_Args>(__args)...);
  235. }
  236.  
  237. template<typename _Functor, typename... _Args>
  238. inline
  239. typename enable_if<
  240. (is_member_pointer<_Functor>::value
  241. && !is_function<_Functor>::value
  242. && !is_function<typename remove_pointer<_Functor>::type>::value),
  243. typename result_of<_Functor(_Args&&...)>::type
  244. >::type
  245. __invoke(_Functor& __f, _Args&&... __args)
  246. {
  247. return std::mem_fn(__f)(std::forward<_Args>(__args)...);
  248. }
  249.  
  250. // To pick up function references (that will become function pointers)
  251. template<typename _Functor, typename... _Args>
  252. inline
  253. typename enable_if<
  254. (is_pointer<_Functor>::value
  255. && is_function<typename remove_pointer<_Functor>::type>::value),
  256. typename result_of<_Functor(_Args&&...)>::type
  257. >::type
  258. __invoke(_Functor __f, _Args&&... __args)
  259. {
  260. return __f(std::forward<_Args>(__args)...);
  261. }
  262.  
  263. /**
  264. * Knowing which of unary_function and binary_function _Tp derives
  265. * from, derives from the same and ensures that reference_wrapper
  266. * will have a weak result type. See cases below.
  267. */
  268. template<bool _Unary, bool _Binary, typename _Tp>
  269. struct _Reference_wrapper_base_impl;
  270.  
  271. // None of the nested argument types.
  272. template<typename _Tp>
  273. struct _Reference_wrapper_base_impl<false, false, _Tp>
  274. : _Weak_result_type<_Tp>
  275. { };
  276.  
  277. // Nested argument_type only.
  278. template<typename _Tp>
  279. struct _Reference_wrapper_base_impl<true, false, _Tp>
  280. : _Weak_result_type<_Tp>
  281. {
  282. typedef typename _Tp::argument_type argument_type;
  283. };
  284.  
  285. // Nested first_argument_type and second_argument_type only.
  286. template<typename _Tp>
  287. struct _Reference_wrapper_base_impl<false, true, _Tp>
  288. : _Weak_result_type<_Tp>
  289. {
  290. typedef typename _Tp::first_argument_type first_argument_type;
  291. typedef typename _Tp::second_argument_type second_argument_type;
  292. };
  293.  
  294. // All the nested argument types.
  295. template<typename _Tp>
  296. struct _Reference_wrapper_base_impl<true, true, _Tp>
  297. : _Weak_result_type<_Tp>
  298. {
  299. typedef typename _Tp::argument_type argument_type;
  300. typedef typename _Tp::first_argument_type first_argument_type;
  301. typedef typename _Tp::second_argument_type second_argument_type;
  302. };
  303.  
  304. _GLIBCXX_HAS_NESTED_TYPE(argument_type)
  305. _GLIBCXX_HAS_NESTED_TYPE(first_argument_type)
  306. _GLIBCXX_HAS_NESTED_TYPE(second_argument_type)
  307.  
  308. /**
  309. * Derives from unary_function or binary_function when it
  310. * can. Specializations handle all of the easy cases. The primary
  311. * template determines what to do with a class type, which may
  312. * derive from both unary_function and binary_function.
  313. */
  314. template<typename _Tp>
  315. struct _Reference_wrapper_base
  316. : _Reference_wrapper_base_impl<
  317. __has_argument_type<_Tp>::value,
  318. __has_first_argument_type<_Tp>::value
  319. && __has_second_argument_type<_Tp>::value,
  320. _Tp>
  321. { };
  322.  
  323. // - a function type (unary)
  324. template<typename _Res, typename _T1>
  325. struct _Reference_wrapper_base<_Res(_T1)>
  326. : unary_function<_T1, _Res>
  327. { };
  328.  
  329. template<typename _Res, typename _T1>
  330. struct _Reference_wrapper_base<_Res(_T1) const>
  331. : unary_function<_T1, _Res>
  332. { };
  333.  
  334. template<typename _Res, typename _T1>
  335. struct _Reference_wrapper_base<_Res(_T1) volatile>
  336. : unary_function<_T1, _Res>
  337. { };
  338.  
  339. template<typename _Res, typename _T1>
  340. struct _Reference_wrapper_base<_Res(_T1) const volatile>
  341. : unary_function<_T1, _Res>
  342. { };
  343.  
  344. // - a function type (binary)
  345. template<typename _Res, typename _T1, typename _T2>
  346. struct _Reference_wrapper_base<_Res(_T1, _T2)>
  347. : binary_function<_T1, _T2, _Res>
  348. { };
  349.  
  350. template<typename _Res, typename _T1, typename _T2>
  351. struct _Reference_wrapper_base<_Res(_T1, _T2) const>
  352. : binary_function<_T1, _T2, _Res>
  353. { };
  354.  
  355. template<typename _Res, typename _T1, typename _T2>
  356. struct _Reference_wrapper_base<_Res(_T1, _T2) volatile>
  357. : binary_function<_T1, _T2, _Res>
  358. { };
  359.  
  360. template<typename _Res, typename _T1, typename _T2>
  361. struct _Reference_wrapper_base<_Res(_T1, _T2) const volatile>
  362. : binary_function<_T1, _T2, _Res>
  363. { };
  364.  
  365. // - a function pointer type (unary)
  366. template<typename _Res, typename _T1>
  367. struct _Reference_wrapper_base<_Res(*)(_T1)>
  368. : unary_function<_T1, _Res>
  369. { };
  370.  
  371. // - a function pointer type (binary)
  372. template<typename _Res, typename _T1, typename _T2>
  373. struct _Reference_wrapper_base<_Res(*)(_T1, _T2)>
  374. : binary_function<_T1, _T2, _Res>
  375. { };
  376.  
  377. // - a pointer to member function type (unary, no qualifiers)
  378. template<typename _Res, typename _T1>
  379. struct _Reference_wrapper_base<_Res (_T1::*)()>
  380. : unary_function<_T1*, _Res>
  381. { };
  382.  
  383. // - a pointer to member function type (binary, no qualifiers)
  384. template<typename _Res, typename _T1, typename _T2>
  385. struct _Reference_wrapper_base<_Res (_T1::*)(_T2)>
  386. : binary_function<_T1*, _T2, _Res>
  387. { };
  388.  
  389. // - a pointer to member function type (unary, const)
  390. template<typename _Res, typename _T1>
  391. struct _Reference_wrapper_base<_Res (_T1::*)() const>
  392. : unary_function<const _T1*, _Res>
  393. { };
  394.  
  395. // - a pointer to member function type (binary, const)
  396. template<typename _Res, typename _T1, typename _T2>
  397. struct _Reference_wrapper_base<_Res (_T1::*)(_T2) const>
  398. : binary_function<const _T1*, _T2, _Res>
  399. { };
  400.  
  401. // - a pointer to member function type (unary, volatile)
  402. template<typename _Res, typename _T1>
  403. struct _Reference_wrapper_base<_Res (_T1::*)() volatile>
  404. : unary_function<volatile _T1*, _Res>
  405. { };
  406.  
  407. // - a pointer to member function type (binary, volatile)
  408. template<typename _Res, typename _T1, typename _T2>
  409. struct _Reference_wrapper_base<_Res (_T1::*)(_T2) volatile>
  410. : binary_function<volatile _T1*, _T2, _Res>
  411. { };
  412.  
  413. // - a pointer to member function type (unary, const volatile)
  414. template<typename _Res, typename _T1>
  415. struct _Reference_wrapper_base<_Res (_T1::*)() const volatile>
  416. : unary_function<const volatile _T1*, _Res>
  417. { };
  418.  
  419. // - a pointer to member function type (binary, const volatile)
  420. template<typename _Res, typename _T1, typename _T2>
  421. struct _Reference_wrapper_base<_Res (_T1::*)(_T2) const volatile>
  422. : binary_function<const volatile _T1*, _T2, _Res>
  423. { };
  424.  
  425. /**
  426. * @brief Primary class template for reference_wrapper.
  427. * @ingroup functors
  428. * @{
  429. */
  430. template<typename _Tp>
  431. class reference_wrapper
  432. : public _Reference_wrapper_base<typename remove_cv<_Tp>::type>
  433. {
  434. _Tp* _M_data;
  435.  
  436. public:
  437. typedef _Tp type;
  438.  
  439. reference_wrapper(_Tp& __indata) noexcept
  440. : _M_data(std::__addressof(__indata))
  441. { }
  442.  
  443. reference_wrapper(_Tp&&) = delete;
  444.  
  445. reference_wrapper(const reference_wrapper<_Tp>& __inref) noexcept
  446. : _M_data(__inref._M_data)
  447. { }
  448.  
  449. reference_wrapper&
  450. operator=(const reference_wrapper<_Tp>& __inref) noexcept
  451. {
  452. _M_data = __inref._M_data;
  453. return *this;
  454. }
  455.  
  456. operator _Tp&() const noexcept
  457. { return this->get(); }
  458.  
  459. _Tp&
  460. get() const noexcept
  461. { return *_M_data; }
  462.  
  463. template<typename... _Args>
  464. typename result_of<_Tp&(_Args&&...)>::type
  465. operator()(_Args&&... __args) const
  466. {
  467. return __invoke(get(), std::forward<_Args>(__args)...);
  468. }
  469. };
  470.  
  471. /// Denotes a reference should be taken to a variable.
  472. template<typename _Tp>
  473. inline reference_wrapper<_Tp>
  474. ref(_Tp& __t) noexcept
  475. { return reference_wrapper<_Tp>(__t); }
  476.  
  477. /// Denotes a const reference should be taken to a variable.
  478. template<typename _Tp>
  479. inline reference_wrapper<const _Tp>
  480. cref(const _Tp& __t) noexcept
  481. { return reference_wrapper<const _Tp>(__t); }
  482.  
  483. template<typename _Tp>
  484. void ref(const _Tp&&) = delete;
  485.  
  486. template<typename _Tp>
  487. void cref(const _Tp&&) = delete;
  488.  
  489. /// Partial specialization.
  490. template<typename _Tp>
  491. inline reference_wrapper<_Tp>
  492. ref(reference_wrapper<_Tp> __t) noexcept
  493. { return ref(__t.get()); }
  494.  
  495. /// Partial specialization.
  496. template<typename _Tp>
  497. inline reference_wrapper<const _Tp>
  498. cref(reference_wrapper<_Tp> __t) noexcept
  499. { return cref(__t.get()); }
  500.  
  501. // @} group functors
  502.  
  503. template<typename... _Types>
  504. struct _Pack : integral_constant<size_t, sizeof...(_Types)>
  505. { };
  506.  
  507. template<typename _From, typename _To, bool = _From::value == _To::value>
  508. struct _AllConvertible : false_type
  509. { };
  510.  
  511. template<typename... _From, typename... _To>
  512. struct _AllConvertible<_Pack<_From...>, _Pack<_To...>, true>
  513. : __and_<is_convertible<_From, _To>...>
  514. { };
  515.  
  516. template<typename _Tp1, typename _Tp2>
  517. using _NotSame = __not_<is_same<typename std::decay<_Tp1>::type,
  518. typename std::decay<_Tp2>::type>>;
  519.  
  520. /**
  521. * Derives from @c unary_function or @c binary_function, or perhaps
  522. * nothing, depending on the number of arguments provided. The
  523. * primary template is the basis case, which derives nothing.
  524. */
  525. template<typename _Res, typename... _ArgTypes>
  526. struct _Maybe_unary_or_binary_function { };
  527.  
  528. /// Derives from @c unary_function, as appropriate.
  529. template<typename _Res, typename _T1>
  530. struct _Maybe_unary_or_binary_function<_Res, _T1>
  531. : std::unary_function<_T1, _Res> { };
  532.  
  533. /// Derives from @c binary_function, as appropriate.
  534. template<typename _Res, typename _T1, typename _T2>
  535. struct _Maybe_unary_or_binary_function<_Res, _T1, _T2>
  536. : std::binary_function<_T1, _T2, _Res> { };
  537.  
  538. /// Implementation of @c mem_fn for member function pointers.
  539. template<typename _Res, typename _Class, typename... _ArgTypes>
  540. class _Mem_fn<_Res (_Class::*)(_ArgTypes...)>
  541. : public _Maybe_unary_or_binary_function<_Res, _Class*, _ArgTypes...>
  542. {
  543. typedef _Res (_Class::*_Functor)(_ArgTypes...);
  544.  
  545. template<typename _Tp, typename... _Args>
  546. _Res
  547. _M_call(_Tp&& __object, const volatile _Class *,
  548. _Args&&... __args) const
  549. {
  550. return (std::forward<_Tp>(__object).*__pmf)
  551. (std::forward<_Args>(__args)...);
  552. }
  553.  
  554. template<typename _Tp, typename... _Args>
  555. _Res
  556. _M_call(_Tp&& __ptr, const volatile void *, _Args&&... __args) const
  557. { return ((*__ptr).*__pmf)(std::forward<_Args>(__args)...); }
  558.  
  559. // Require each _Args to be convertible to corresponding _ArgTypes
  560. template<typename... _Args>
  561. using _RequireValidArgs
  562. = _Require<_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  563.  
  564. // Require each _Args to be convertible to corresponding _ArgTypes
  565. // and require _Tp is not _Class, _Class& or _Class*
  566. template<typename _Tp, typename... _Args>
  567. using _RequireValidArgs2
  568. = _Require<_NotSame<_Class, _Tp>, _NotSame<_Class*, _Tp>,
  569. _AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  570.  
  571. // Require each _Args to be convertible to corresponding _ArgTypes
  572. // and require _Tp is _Class or derived from _Class
  573. template<typename _Tp, typename... _Args>
  574. using _RequireValidArgs3
  575. = _Require<is_base_of<_Class, _Tp>,
  576. _AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  577.  
  578. public:
  579. typedef _Res result_type;
  580.  
  581. explicit _Mem_fn(_Functor __pmf) : __pmf(__pmf) { }
  582.  
  583. // Handle objects
  584. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  585. _Res
  586. operator()(_Class& __object, _Args&&... __args) const
  587. { return (__object.*__pmf)(std::forward<_Args>(__args)...); }
  588.  
  589. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  590. _Res
  591. operator()(_Class&& __object, _Args&&... __args) const
  592. {
  593. return (std::move(__object).*__pmf)(std::forward<_Args>(__args)...);
  594. }
  595.  
  596. // Handle pointers
  597. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  598. _Res
  599. operator()(_Class* __object, _Args&&... __args) const
  600. { return (__object->*__pmf)(std::forward<_Args>(__args)...); }
  601.  
  602. // Handle smart pointers, references and pointers to derived
  603. template<typename _Tp, typename... _Args,
  604. typename _Req = _RequireValidArgs2<_Tp, _Args...>>
  605. _Res
  606. operator()(_Tp&& __object, _Args&&... __args) const
  607. {
  608. return _M_call(std::forward<_Tp>(__object), &__object,
  609. std::forward<_Args>(__args)...);
  610. }
  611.  
  612. template<typename _Tp, typename... _Args,
  613. typename _Req = _RequireValidArgs3<_Tp, _Args...>>
  614. _Res
  615. operator()(reference_wrapper<_Tp> __ref, _Args&&... __args) const
  616. { return operator()(__ref.get(), std::forward<_Args>(__args)...); }
  617.  
  618. private:
  619. _Functor __pmf;
  620. };
  621.  
  622. /// Implementation of @c mem_fn for const member function pointers.
  623. template<typename _Res, typename _Class, typename... _ArgTypes>
  624. class _Mem_fn<_Res (_Class::*)(_ArgTypes...) const>
  625. : public _Maybe_unary_or_binary_function<_Res, const _Class*,
  626. _ArgTypes...>
  627. {
  628. typedef _Res (_Class::*_Functor)(_ArgTypes...) const;
  629.  
  630. template<typename _Tp, typename... _Args>
  631. _Res
  632. _M_call(_Tp&& __object, const volatile _Class *,
  633. _Args&&... __args) const
  634. {
  635. return (std::forward<_Tp>(__object).*__pmf)
  636. (std::forward<_Args>(__args)...);
  637. }
  638.  
  639. template<typename _Tp, typename... _Args>
  640. _Res
  641. _M_call(_Tp&& __ptr, const volatile void *, _Args&&... __args) const
  642. { return ((*__ptr).*__pmf)(std::forward<_Args>(__args)...); }
  643.  
  644. template<typename... _Args>
  645. using _RequireValidArgs
  646. = _Require<_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  647.  
  648. template<typename _Tp, typename... _Args>
  649. using _RequireValidArgs2
  650. = _Require<_NotSame<_Class, _Tp>, _NotSame<const _Class*, _Tp>,
  651. _AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  652.  
  653. template<typename _Tp, typename... _Args>
  654. using _RequireValidArgs3
  655. = _Require<is_base_of<_Class, _Tp>,
  656. _AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  657.  
  658. public:
  659. typedef _Res result_type;
  660.  
  661. explicit _Mem_fn(_Functor __pmf) : __pmf(__pmf) { }
  662.  
  663. // Handle objects
  664. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  665. _Res
  666. operator()(const _Class& __object, _Args&&... __args) const
  667. { return (__object.*__pmf)(std::forward<_Args>(__args)...); }
  668.  
  669. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  670. _Res
  671. operator()(const _Class&& __object, _Args&&... __args) const
  672. {
  673. return (std::move(__object).*__pmf)(std::forward<_Args>(__args)...);
  674. }
  675.  
  676. // Handle pointers
  677. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  678. _Res
  679. operator()(const _Class* __object, _Args&&... __args) const
  680. { return (__object->*__pmf)(std::forward<_Args>(__args)...); }
  681.  
  682. // Handle smart pointers, references and pointers to derived
  683. template<typename _Tp, typename... _Args,
  684. typename _Req = _RequireValidArgs2<_Tp, _Args...>>
  685. _Res operator()(_Tp&& __object, _Args&&... __args) const
  686. {
  687. return _M_call(std::forward<_Tp>(__object), &__object,
  688. std::forward<_Args>(__args)...);
  689. }
  690.  
  691. template<typename _Tp, typename... _Args,
  692. typename _Req = _RequireValidArgs3<_Tp, _Args...>>
  693. _Res
  694. operator()(reference_wrapper<_Tp> __ref, _Args&&... __args) const
  695. { return operator()(__ref.get(), std::forward<_Args>(__args)...); }
  696.  
  697. private:
  698. _Functor __pmf;
  699. };
  700.  
  701. /// Implementation of @c mem_fn for volatile member function pointers.
  702. template<typename _Res, typename _Class, typename... _ArgTypes>
  703. class _Mem_fn<_Res (_Class::*)(_ArgTypes...) volatile>
  704. : public _Maybe_unary_or_binary_function<_Res, volatile _Class*,
  705. _ArgTypes...>
  706. {
  707. typedef _Res (_Class::*_Functor)(_ArgTypes...) volatile;
  708.  
  709. template<typename _Tp, typename... _Args>
  710. _Res
  711. _M_call(_Tp&& __object, const volatile _Class *,
  712. _Args&&... __args) const
  713. {
  714. return (std::forward<_Tp>(__object).*__pmf)
  715. (std::forward<_Args>(__args)...);
  716. }
  717.  
  718. template<typename _Tp, typename... _Args>
  719. _Res
  720. _M_call(_Tp&& __ptr, const volatile void *, _Args&&... __args) const
  721. { return ((*__ptr).*__pmf)(std::forward<_Args>(__args)...); }
  722.  
  723. template<typename... _Args>
  724. using _RequireValidArgs
  725. = _Require<_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  726.  
  727. template<typename _Tp, typename... _Args>
  728. using _RequireValidArgs2
  729. = _Require<_NotSame<_Class, _Tp>, _NotSame<volatile _Class*, _Tp>,
  730. _AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  731.  
  732. template<typename _Tp, typename... _Args>
  733. using _RequireValidArgs3
  734. = _Require<is_base_of<_Class, _Tp>,
  735. _AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  736.  
  737. public:
  738. typedef _Res result_type;
  739.  
  740. explicit _Mem_fn(_Functor __pmf) : __pmf(__pmf) { }
  741.  
  742. // Handle objects
  743. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  744. _Res
  745. operator()(volatile _Class& __object, _Args&&... __args) const
  746. { return (__object.*__pmf)(std::forward<_Args>(__args)...); }
  747.  
  748. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  749. _Res
  750. operator()(volatile _Class&& __object, _Args&&... __args) const
  751. {
  752. return (std::move(__object).*__pmf)(std::forward<_Args>(__args)...);
  753. }
  754.  
  755. // Handle pointers
  756. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  757. _Res
  758. operator()(volatile _Class* __object, _Args&&... __args) const
  759. { return (__object->*__pmf)(std::forward<_Args>(__args)...); }
  760.  
  761. // Handle smart pointers, references and pointers to derived
  762. template<typename _Tp, typename... _Args,
  763. typename _Req = _RequireValidArgs2<_Tp, _Args...>>
  764. _Res
  765. operator()(_Tp&& __object, _Args&&... __args) const
  766. {
  767. return _M_call(std::forward<_Tp>(__object), &__object,
  768. std::forward<_Args>(__args)...);
  769. }
  770.  
  771. template<typename _Tp, typename... _Args,
  772. typename _Req = _RequireValidArgs3<_Tp, _Args...>>
  773. _Res
  774. operator()(reference_wrapper<_Tp> __ref, _Args&&... __args) const
  775. { return operator()(__ref.get(), std::forward<_Args>(__args)...); }
  776.  
  777. private:
  778. _Functor __pmf;
  779. };
  780.  
  781. /// Implementation of @c mem_fn for const volatile member function pointers.
  782. template<typename _Res, typename _Class, typename... _ArgTypes>
  783. class _Mem_fn<_Res (_Class::*)(_ArgTypes...) const volatile>
  784. : public _Maybe_unary_or_binary_function<_Res, const volatile _Class*,
  785. _ArgTypes...>
  786. {
  787. typedef _Res (_Class::*_Functor)(_ArgTypes...) const volatile;
  788.  
  789. template<typename _Tp, typename... _Args>
  790. _Res
  791. _M_call(_Tp&& __object, const volatile _Class *,
  792. _Args&&... __args) const
  793. {
  794. return (std::forward<_Tp>(__object).*__pmf)
  795. (std::forward<_Args>(__args)...);
  796. }
  797.  
  798. template<typename _Tp, typename... _Args>
  799. _Res
  800. _M_call(_Tp&& __ptr, const volatile void *, _Args&&... __args) const
  801. { return ((*__ptr).*__pmf)(std::forward<_Args>(__args)...); }
  802.  
  803. template<typename... _Args>
  804. using _RequireValidArgs
  805. = _Require<_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  806.  
  807. template<typename _Tp, typename... _Args>
  808. using _RequireValidArgs2
  809. = _Require<_NotSame<_Class, _Tp>,
  810. _NotSame<const volatile _Class*, _Tp>,
  811. _AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  812.  
  813. template<typename _Tp, typename... _Args>
  814. using _RequireValidArgs3
  815. = _Require<is_base_of<_Class, _Tp>,
  816. _AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>;
  817.  
  818. public:
  819. typedef _Res result_type;
  820.  
  821. explicit _Mem_fn(_Functor __pmf) : __pmf(__pmf) { }
  822.  
  823. // Handle objects
  824. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  825. _Res
  826. operator()(const volatile _Class& __object, _Args&&... __args) const
  827. { return (__object.*__pmf)(std::forward<_Args>(__args)...); }
  828.  
  829. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  830. _Res
  831. operator()(const volatile _Class&& __object, _Args&&... __args) const
  832. {
  833. return (std::move(__object).*__pmf)(std::forward<_Args>(__args)...);
  834. }
  835.  
  836. // Handle pointers
  837. template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
  838. _Res
  839. operator()(const volatile _Class* __object, _Args&&... __args) const
  840. { return (__object->*__pmf)(std::forward<_Args>(__args)...); }
  841.  
  842. // Handle smart pointers, references and pointers to derived
  843. template<typename _Tp, typename... _Args,
  844. typename _Req = _RequireValidArgs2<_Tp, _Args...>>
  845. _Res operator()(_Tp&& __object, _Args&&... __args) const
  846. {
  847. return _M_call(std::forward<_Tp>(__object), &__object,
  848. std::forward<_Args>(__args)...);
  849. }
  850.  
  851. template<typename _Tp, typename... _Args,
  852. typename _Req = _RequireValidArgs3<_Tp, _Args...>>
  853. _Res
  854. operator()(reference_wrapper<_Tp> __ref, _Args&&... __args) const
  855. { return operator()(__ref.get(), std::forward<_Args>(__args)...); }
  856.  
  857. private:
  858. _Functor __pmf;
  859. };
  860.  
  861. template<typename _Tp, bool>
  862. struct _Mem_fn_const_or_non
  863. {
  864. typedef const _Tp& type;
  865. };
  866.  
  867. template<typename _Tp>
  868. struct _Mem_fn_const_or_non<_Tp, false>
  869. {
  870. typedef _Tp& type;
  871. };
  872.  
  873. template<typename _Res, typename _Class>
  874. class _Mem_fn<_Res _Class::*>
  875. {
  876. using __pm_type = _Res _Class::*;
  877.  
  878. // This bit of genius is due to Peter Dimov, improved slightly by
  879. // Douglas Gregor.
  880. // Made less elegant to support perfect forwarding and noexcept.
  881. template<typename _Tp>
  882. auto
  883. _M_call(_Tp&& __object, const _Class *) const noexcept
  884. -> decltype(std::forward<_Tp>(__object).*std::declval<__pm_type&>())
  885. { return std::forward<_Tp>(__object).*__pm; }
  886.  
  887. template<typename _Tp, typename _Up>
  888. auto
  889. _M_call(_Tp&& __object, _Up * const *) const noexcept
  890. -> decltype((*std::forward<_Tp>(__object)).*std::declval<__pm_type&>())
  891. { return (*std::forward<_Tp>(__object)).*__pm; }
  892.  
  893. template<typename _Tp>
  894. auto
  895. _M_call(_Tp&& __ptr, const volatile void*) const
  896. noexcept(noexcept((*__ptr).*std::declval<__pm_type&>()))
  897. -> decltype((*__ptr).*std::declval<__pm_type&>())
  898. { return (*__ptr).*__pm; }
  899.  
  900. public:
  901. explicit
  902. _Mem_fn(_Res _Class::*__pm) noexcept : __pm(__pm) { }
  903.  
  904. // Handle objects
  905. _Res&
  906. operator()(_Class& __object) const noexcept
  907. { return __object.*__pm; }
  908.  
  909. const _Res&
  910. operator()(const _Class& __object) const noexcept
  911. { return __object.*__pm; }
  912.  
  913. _Res&&
  914. operator()(_Class&& __object) const noexcept
  915. { return std::forward<_Class>(__object).*__pm; }
  916.  
  917. const _Res&&
  918. operator()(const _Class&& __object) const noexcept
  919. { return std::forward<const _Class>(__object).*__pm; }
  920.  
  921. // Handle pointers
  922. _Res&
  923. operator()(_Class* __object) const noexcept
  924. { return __object->*__pm; }
  925.  
  926. const _Res&
  927. operator()(const _Class* __object) const noexcept
  928. { return __object->*__pm; }
  929.  
  930. // Handle smart pointers and derived
  931. template<typename _Tp, typename _Req = _Require<_NotSame<_Class*, _Tp>>>
  932. auto
  933. operator()(_Tp&& __unknown) const
  934. noexcept(noexcept(std::declval<_Mem_fn*>()->_M_call
  935. (std::forward<_Tp>(__unknown), &__unknown)))
  936. -> decltype(this->_M_call(std::forward<_Tp>(__unknown), &__unknown))
  937. { return _M_call(std::forward<_Tp>(__unknown), &__unknown); }
  938.  
  939. template<typename _Tp, typename _Req = _Require<is_base_of<_Class, _Tp>>>
  940. auto
  941. operator()(reference_wrapper<_Tp> __ref) const
  942. noexcept(noexcept(std::declval<_Mem_fn&>()(__ref.get())))
  943. -> decltype((*this)(__ref.get()))
  944. { return (*this)(__ref.get()); }
  945.  
  946. private:
  947. _Res _Class::*__pm;
  948. };
  949.  
  950. // _GLIBCXX_RESOLVE_LIB_DEFECTS
  951. // 2048. Unnecessary mem_fn overloads
  952. /**
  953. * @brief Returns a function object that forwards to the member
  954. * pointer @a pm.
  955. * @ingroup functors
  956. */
  957. template<typename _Tp, typename _Class>
  958. inline _Mem_fn<_Tp _Class::*>
  959. mem_fn(_Tp _Class::* __pm) noexcept
  960. {
  961. return _Mem_fn<_Tp _Class::*>(__pm);
  962. }
  963.  
  964. /**
  965. * @brief Determines if the given type _Tp is a function object
  966. * should be treated as a subexpression when evaluating calls to
  967. * function objects returned by bind(). [TR1 3.6.1]
  968. * @ingroup binders
  969. */
  970. template<typename _Tp>
  971. struct is_bind_expression
  972. : public false_type { };
  973.  
  974. /**
  975. * @brief Determines if the given type _Tp is a placeholder in a
  976. * bind() expression and, if so, which placeholder it is. [TR1 3.6.2]
  977. * @ingroup binders
  978. */
  979. template<typename _Tp>
  980. struct is_placeholder
  981. : public integral_constant<int, >
  982. { };
  983.  
  984. /** @brief The type of placeholder objects defined by libstdc++.
  985. * @ingroup binders
  986. */
  987. template<int _Num> struct _Placeholder { };
  988.  
  989. _GLIBCXX_END_NAMESPACE_VERSION
  990.  
  991. /** @namespace std::placeholders
  992. * @brief ISO C++11 entities sub-namespace for functional.
  993. * @ingroup binders
  994. */
  995. namespace placeholders
  996. {
  997. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  998. /* Define a large number of placeholders. There is no way to
  999. * simplify this with variadic templates, because we're introducing
  1000. * unique names for each.
  1001. */
  1002. extern const _Placeholder<> _1;
  1003. extern const _Placeholder<> _2;
  1004. extern const _Placeholder<> _3;
  1005. extern const _Placeholder<> _4;
  1006. extern const _Placeholder<> _5;
  1007. extern const _Placeholder<> _6;
  1008. extern const _Placeholder<> _7;
  1009. extern const _Placeholder<> _8;
  1010. extern const _Placeholder<> _9;
  1011. extern const _Placeholder<> _10;
  1012. extern const _Placeholder<> _11;
  1013. extern const _Placeholder<> _12;
  1014. extern const _Placeholder<> _13;
  1015. extern const _Placeholder<> _14;
  1016. extern const _Placeholder<> _15;
  1017. extern const _Placeholder<> _16;
  1018. extern const _Placeholder<> _17;
  1019. extern const _Placeholder<> _18;
  1020. extern const _Placeholder<> _19;
  1021. extern const _Placeholder<> _20;
  1022. extern const _Placeholder<> _21;
  1023. extern const _Placeholder<> _22;
  1024. extern const _Placeholder<> _23;
  1025. extern const _Placeholder<> _24;
  1026. extern const _Placeholder<> _25;
  1027. extern const _Placeholder<> _26;
  1028. extern const _Placeholder<> _27;
  1029. extern const _Placeholder<> _28;
  1030. extern const _Placeholder<> _29;
  1031. _GLIBCXX_END_NAMESPACE_VERSION
  1032. }
  1033.  
  1034. _GLIBCXX_BEGIN_NAMESPACE_VERSION
  1035.  
  1036. /**
  1037. * Partial specialization of is_placeholder that provides the placeholder
  1038. * number for the placeholder objects defined by libstdc++.
  1039. * @ingroup binders
  1040. */
  1041. template<int _Num>
  1042. struct is_placeholder<_Placeholder<_Num> >
  1043. : public integral_constant<int, _Num>
  1044. { };
  1045.  
  1046. template<int _Num>
  1047. struct is_placeholder<const _Placeholder<_Num> >
  1048. : public integral_constant<int, _Num>
  1049. { };
  1050.  
  1051. /**
  1052. * Used by _Safe_tuple_element to indicate that there is no tuple
  1053. * element at this position.
  1054. */
  1055. struct _No_tuple_element;
  1056.  
  1057. /**
  1058. * Implementation helper for _Safe_tuple_element. This primary
  1059. * template handles the case where it is safe to use @c
  1060. * tuple_element.
  1061. */
  1062. template<std::size_t __i, typename _Tuple, bool _IsSafe>
  1063. struct _Safe_tuple_element_impl
  1064. : tuple_element<__i, _Tuple> { };
  1065.  
  1066. /**
  1067. * Implementation helper for _Safe_tuple_element. This partial
  1068. * specialization handles the case where it is not safe to use @c
  1069. * tuple_element. We just return @c _No_tuple_element.
  1070. */
  1071. template<std::size_t __i, typename _Tuple>
  1072. struct _Safe_tuple_element_impl<__i, _Tuple, false>
  1073. {
  1074. typedef _No_tuple_element type;
  1075. };
  1076.  
  1077. /**
  1078. * Like tuple_element, but returns @c _No_tuple_element when
  1079. * tuple_element would return an error.
  1080. */
  1081. template<std::size_t __i, typename _Tuple>
  1082. struct _Safe_tuple_element
  1083. : _Safe_tuple_element_impl<__i, _Tuple,
  1084. (__i < tuple_size<_Tuple>::value)>
  1085. { };
  1086.  
  1087. /**
  1088. * Maps an argument to bind() into an actual argument to the bound
  1089. * function object [TR1 3.6.3/5]. Only the first parameter should
  1090. * be specified: the rest are used to determine among the various
  1091. * implementations. Note that, although this class is a function
  1092. * object, it isn't entirely normal because it takes only two
  1093. * parameters regardless of the number of parameters passed to the
  1094. * bind expression. The first parameter is the bound argument and
  1095. * the second parameter is a tuple containing references to the
  1096. * rest of the arguments.
  1097. */
  1098. template<typename _Arg,
  1099. bool _IsBindExp = is_bind_expression<_Arg>::value,
  1100. bool _IsPlaceholder = (is_placeholder<_Arg>::value > )>
  1101. class _Mu;
  1102.  
  1103. /**
  1104. * If the argument is reference_wrapper<_Tp>, returns the
  1105. * underlying reference. [TR1 3.6.3/5 bullet 1]
  1106. */
  1107. template<typename _Tp>
  1108. class _Mu<reference_wrapper<_Tp>, false, false>
  1109. {
  1110. public:
  1111. typedef _Tp& result_type;
  1112.  
  1113. /* Note: This won't actually work for const volatile
  1114. * reference_wrappers, because reference_wrapper::get() is const
  1115. * but not volatile-qualified. This might be a defect in the TR.
  1116. */
  1117. template<typename _CVRef, typename _Tuple>
  1118. result_type
  1119. operator()(_CVRef& __arg, _Tuple&) const volatile
  1120. { return __arg.get(); }
  1121. };
  1122.  
  1123. /**
  1124. * If the argument is a bind expression, we invoke the underlying
  1125. * function object with the same cv-qualifiers as we are given and
  1126. * pass along all of our arguments (unwrapped). [TR1 3.6.3/5 bullet 2]
  1127. */
  1128. template<typename _Arg>
  1129. class _Mu<_Arg, true, false>
  1130. {
  1131. public:
  1132. template<typename _CVArg, typename... _Args>
  1133. auto
  1134. operator()(_CVArg& __arg,
  1135. tuple<_Args...>& __tuple) const volatile
  1136. -> decltype(__arg(declval<_Args>()...))
  1137. {
  1138. // Construct an index tuple and forward to __call
  1139. typedef typename _Build_index_tuple<sizeof...(_Args)>::__type
  1140. _Indexes;
  1141. return this->__call(__arg, __tuple, _Indexes());
  1142. }
  1143.  
  1144. private:
  1145. // Invokes the underlying function object __arg by unpacking all
  1146. // of the arguments in the tuple.
  1147. template<typename _CVArg, typename... _Args, std::size_t... _Indexes>
  1148. auto
  1149. __call(_CVArg& __arg, tuple<_Args...>& __tuple,
  1150. const _Index_tuple<_Indexes...>&) const volatile
  1151. -> decltype(__arg(declval<_Args>()...))
  1152. {
  1153. return __arg(std::forward<_Args>(get<_Indexes>(__tuple))...);
  1154. }
  1155. };
  1156.  
  1157. /**
  1158. * If the argument is a placeholder for the Nth argument, returns
  1159. * a reference to the Nth argument to the bind function object.
  1160. * [TR1 3.6.3/5 bullet 3]
  1161. */
  1162. template<typename _Arg>
  1163. class _Mu<_Arg, false, true>
  1164. {
  1165. public:
  1166. template<typename _Signature> class result;
  1167.  
  1168. template<typename _CVMu, typename _CVArg, typename _Tuple>
  1169. class result<_CVMu(_CVArg, _Tuple)>
  1170. {
  1171. // Add a reference, if it hasn't already been done for us.
  1172. // This allows us to be a little bit sloppy in constructing
  1173. // the tuple that we pass to result_of<...>.
  1174. typedef typename _Safe_tuple_element<(is_placeholder<_Arg>::value
  1175. - ), _Tuple>::type
  1176. __base_type;
  1177.  
  1178. public:
  1179. typedef typename add_rvalue_reference<__base_type>::type type;
  1180. };
  1181.  
  1182. template<typename _Tuple>
  1183. typename result<_Mu(_Arg, _Tuple)>::type
  1184. operator()(const volatile _Arg&, _Tuple& __tuple) const volatile
  1185. {
  1186. return std::forward<typename result<_Mu(_Arg, _Tuple)>::type>(
  1187. ::std::get<(is_placeholder<_Arg>::value - )>(__tuple));
  1188. }
  1189. };
  1190.  
  1191. /**
  1192. * If the argument is just a value, returns a reference to that
  1193. * value. The cv-qualifiers on the reference are the same as the
  1194. * cv-qualifiers on the _Mu object. [TR1 3.6.3/5 bullet 4]
  1195. */
  1196. template<typename _Arg>
  1197. class _Mu<_Arg, false, false>
  1198. {
  1199. public:
  1200. template<typename _Signature> struct result;
  1201.  
  1202. template<typename _CVMu, typename _CVArg, typename _Tuple>
  1203. struct result<_CVMu(_CVArg, _Tuple)>
  1204. {
  1205. typedef typename add_lvalue_reference<_CVArg>::type type;
  1206. };
  1207.  
  1208. // Pick up the cv-qualifiers of the argument
  1209. template<typename _CVArg, typename _Tuple>
  1210. _CVArg&&
  1211. operator()(_CVArg&& __arg, _Tuple&) const volatile
  1212. { return std::forward<_CVArg>(__arg); }
  1213. };
  1214.  
  1215. /**
  1216. * Maps member pointers into instances of _Mem_fn but leaves all
  1217. * other function objects untouched. Used by tr1::bind(). The
  1218. * primary template handles the non--member-pointer case.
  1219. */
  1220. template<typename _Tp>
  1221. struct _Maybe_wrap_member_pointer
  1222. {
  1223. typedef _Tp type;
  1224.  
  1225. static const _Tp&
  1226. __do_wrap(const _Tp& __x)
  1227. { return __x; }
  1228.  
  1229. static _Tp&&
  1230. __do_wrap(_Tp&& __x)
  1231. { return static_cast<_Tp&&>(__x); }
  1232. };
  1233.  
  1234. /**
  1235. * Maps member pointers into instances of _Mem_fn but leaves all
  1236. * other function objects untouched. Used by tr1::bind(). This
  1237. * partial specialization handles the member pointer case.
  1238. */
  1239. template<typename _Tp, typename _Class>
  1240. struct _Maybe_wrap_member_pointer<_Tp _Class::*>
  1241. {
  1242. typedef _Mem_fn<_Tp _Class::*> type;
  1243.  
  1244. static type
  1245. __do_wrap(_Tp _Class::* __pm)
  1246. { return type(__pm); }
  1247. };
  1248.  
  1249. // Specialization needed to prevent "forming reference to void" errors when
  1250. // bind<void>() is called, because argument deduction instantiates
  1251. // _Maybe_wrap_member_pointer<void> outside the immediate context where
  1252. // SFINAE applies.
  1253. template<>
  1254. struct _Maybe_wrap_member_pointer<void>
  1255. {
  1256. typedef void type;
  1257. };
  1258.  
  1259. // std::get<I> for volatile-qualified tuples
  1260. template<std::size_t _Ind, typename... _Tp>
  1261. inline auto
  1262. __volget(volatile tuple<_Tp...>& __tuple)
  1263. -> typename tuple_element<_Ind, tuple<_Tp...>>::type volatile&
  1264. { return std::get<_Ind>(const_cast<tuple<_Tp...>&>(__tuple)); }
  1265.  
  1266. // std::get<I> for const-volatile-qualified tuples
  1267. template<std::size_t _Ind, typename... _Tp>
  1268. inline auto
  1269. __volget(const volatile tuple<_Tp...>& __tuple)
  1270. -> typename tuple_element<_Ind, tuple<_Tp...>>::type const volatile&
  1271. { return std::get<_Ind>(const_cast<const tuple<_Tp...>&>(__tuple)); }
  1272.  
  1273. /// Type of the function object returned from bind().
  1274. template<typename _Signature>
  1275. struct _Bind;
  1276.  
  1277. template<typename _Functor, typename... _Bound_args>
  1278. class _Bind<_Functor(_Bound_args...)>
  1279. : public _Weak_result_type<_Functor>
  1280. {
  1281. typedef _Bind __self_type;
  1282. typedef typename _Build_index_tuple<sizeof...(_Bound_args)>::__type
  1283. _Bound_indexes;
  1284.  
  1285. _Functor _M_f;
  1286. tuple<_Bound_args...> _M_bound_args;
  1287.  
  1288. // Call unqualified
  1289. template<typename _Result, typename... _Args, std::size_t... _Indexes>
  1290. _Result
  1291. __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>)
  1292. {
  1293. return _M_f(_Mu<_Bound_args>()
  1294. (get<_Indexes>(_M_bound_args), __args)...);
  1295. }
  1296.  
  1297. // Call as const
  1298. template<typename _Result, typename... _Args, std::size_t... _Indexes>
  1299. _Result
  1300. __call_c(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const
  1301. {
  1302. return _M_f(_Mu<_Bound_args>()
  1303. (get<_Indexes>(_M_bound_args), __args)...);
  1304. }
  1305.  
  1306. // Call as volatile
  1307. template<typename _Result, typename... _Args, std::size_t... _Indexes>
  1308. _Result
  1309. __call_v(tuple<_Args...>&& __args,
  1310. _Index_tuple<_Indexes...>) volatile
  1311. {
  1312. return _M_f(_Mu<_Bound_args>()
  1313. (__volget<_Indexes>(_M_bound_args), __args)...);
  1314. }
  1315.  
  1316. // Call as const volatile
  1317. template<typename _Result, typename... _Args, std::size_t... _Indexes>
  1318. _Result
  1319. __call_c_v(tuple<_Args...>&& __args,
  1320. _Index_tuple<_Indexes...>) const volatile
  1321. {
  1322. return _M_f(_Mu<_Bound_args>()
  1323. (__volget<_Indexes>(_M_bound_args), __args)...);
  1324. }
  1325.  
  1326. public:
  1327. template<typename... _Args>
  1328. explicit _Bind(const _Functor& __f, _Args&&... __args)
  1329. : _M_f(__f), _M_bound_args(std::forward<_Args>(__args)...)
  1330. { }
  1331.  
  1332. template<typename... _Args>
  1333. explicit _Bind(_Functor&& __f, _Args&&... __args)
  1334. : _M_f(std::move(__f)), _M_bound_args(std::forward<_Args>(__args)...)
  1335. { }
  1336.  
  1337. _Bind(const _Bind&) = default;
  1338.  
  1339. _Bind(_Bind&& __b)
  1340. : _M_f(std::move(__b._M_f)), _M_bound_args(std::move(__b._M_bound_args))
  1341. { }
  1342.  
  1343. // Call unqualified
  1344. template<typename... _Args, typename _Result
  1345. = decltype( std::declval<_Functor>()(
  1346. _Mu<_Bound_args>()( std::declval<_Bound_args&>(),
  1347. std::declval<tuple<_Args...>&>() )... ) )>
  1348. _Result
  1349. operator()(_Args&&... __args)
  1350. {
  1351. return this->__call<_Result>(
  1352. std::forward_as_tuple(std::forward<_Args>(__args)...),
  1353. _Bound_indexes());
  1354. }
  1355.  
  1356. // Call as const
  1357. template<typename... _Args, typename _Result
  1358. = decltype( std::declval<typename enable_if<(sizeof...(_Args) >= ),
  1359. typename add_const<_Functor>::type>::type>()(
  1360. _Mu<_Bound_args>()( std::declval<const _Bound_args&>(),
  1361. std::declval<tuple<_Args...>&>() )... ) )>
  1362. _Result
  1363. operator()(_Args&&... __args) const
  1364. {
  1365. return this->__call_c<_Result>(
  1366. std::forward_as_tuple(std::forward<_Args>(__args)...),
  1367. _Bound_indexes());
  1368. }
  1369.  
  1370. // Call as volatile
  1371. template<typename... _Args, typename _Result
  1372. = decltype( std::declval<typename enable_if<(sizeof...(_Args) >= ),
  1373. typename add_volatile<_Functor>::type>::type>()(
  1374. _Mu<_Bound_args>()( std::declval<volatile _Bound_args&>(),
  1375. std::declval<tuple<_Args...>&>() )... ) )>
  1376. _Result
  1377. operator()(_Args&&... __args) volatile
  1378. {
  1379. return this->__call_v<_Result>(
  1380. std::forward_as_tuple(std::forward<_Args>(__args)...),
  1381. _Bound_indexes());
  1382. }
  1383.  
  1384. // Call as const volatile
  1385. template<typename... _Args, typename _Result
  1386. = decltype( std::declval<typename enable_if<(sizeof...(_Args) >= ),
  1387. typename add_cv<_Functor>::type>::type>()(
  1388. _Mu<_Bound_args>()( std::declval<const volatile _Bound_args&>(),
  1389. std::declval<tuple<_Args...>&>() )... ) )>
  1390. _Result
  1391. operator()(_Args&&... __args) const volatile
  1392. {
  1393. return this->__call_c_v<_Result>(
  1394. std::forward_as_tuple(std::forward<_Args>(__args)...),
  1395. _Bound_indexes());
  1396. }
  1397. };
  1398.  
  1399. /// Type of the function object returned from bind<R>().
  1400. template<typename _Result, typename _Signature>
  1401. struct _Bind_result;
  1402.  
  1403. template<typename _Result, typename _Functor, typename... _Bound_args>
  1404. class _Bind_result<_Result, _Functor(_Bound_args...)>
  1405. {
  1406. typedef _Bind_result __self_type;
  1407. typedef typename _Build_index_tuple<sizeof...(_Bound_args)>::__type
  1408. _Bound_indexes;
  1409.  
  1410. _Functor _M_f;
  1411. tuple<_Bound_args...> _M_bound_args;
  1412.  
  1413. // sfinae types
  1414. template<typename _Res>
  1415. struct __enable_if_void : enable_if<is_void<_Res>::value, int> { };
  1416. template<typename _Res>
  1417. struct __disable_if_void : enable_if<!is_void<_Res>::value, int> { };
  1418.  
  1419. // Call unqualified
  1420. template<typename _Res, typename... _Args, std::size_t... _Indexes>
  1421. _Result
  1422. __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
  1423. typename __disable_if_void<_Res>::type = )
  1424. {
  1425. return _M_f(_Mu<_Bound_args>()
  1426. (get<_Indexes>(_M_bound_args), __args)...);
  1427. }
  1428.  
  1429. // Call unqualified, return void
  1430. template<typename _Res, typename... _Args, std::size_t... _Indexes>
  1431. void
  1432. __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
  1433. typename __enable_if_void<_Res>::type = )
  1434. {
  1435. _M_f(_Mu<_Bound_args>()
  1436. (get<_Indexes>(_M_bound_args), __args)...);
  1437. }
  1438.  
  1439. // Call as const
  1440. template<typename _Res, typename... _Args, std::size_t... _Indexes>
  1441. _Result
  1442. __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
  1443. typename __disable_if_void<_Res>::type = ) const
  1444. {
  1445. return _M_f(_Mu<_Bound_args>()
  1446. (get<_Indexes>(_M_bound_args), __args)...);
  1447. }
  1448.  
  1449. // Call as const, return void
  1450. template<typename _Res, typename... _Args, std::size_t... _Indexes>
  1451. void
  1452. __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
  1453. typename __enable_if_void<_Res>::type = ) const
  1454. {
  1455. _M_f(_Mu<_Bound_args>()
  1456. (get<_Indexes>(_M_bound_args), __args)...);
  1457. }
  1458.  
  1459. // Call as volatile
  1460. template<typename _Res, typename... _Args, std::size_t... _Indexes>
  1461. _Result
  1462. __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
  1463. typename __disable_if_void<_Res>::type = ) volatile
  1464. {
  1465. return _M_f(_Mu<_Bound_args>()
  1466. (__volget<_Indexes>(_M_bound_args), __args)...);
  1467. }
  1468.  
  1469. // Call as volatile, return void
  1470. template<typename _Res, typename... _Args, std::size_t... _Indexes>
  1471. void
  1472. __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
  1473. typename __enable_if_void<_Res>::type = ) volatile
  1474. {
  1475. _M_f(_Mu<_Bound_args>()
  1476. (__volget<_Indexes>(_M_bound_args), __args)...);
  1477. }
  1478.  
  1479. // Call as const volatile
  1480. template<typename _Res, typename... _Args, std::size_t... _Indexes>
  1481. _Result
  1482. __call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
  1483. typename __disable_if_void<_Res>::type = ) const volatile
  1484. {
  1485. return _M_f(_Mu<_Bound_args>()
  1486. (__volget<_Indexes>(_M_bound_args), __args)...);
  1487. }
  1488.  
  1489. // Call as const volatile, return void
  1490. template<typename _Res, typename... _Args, std::size_t... _Indexes>
  1491. void
  1492. __call(tuple<_Args...>&& __args,
  1493. _Index_tuple<_Indexes...>,
  1494. typename __enable_if_void<_Res>::type = ) const volatile
  1495. {
  1496. _M_f(_Mu<_Bound_args>()
  1497. (__volget<_Indexes>(_M_bound_args), __args)...);
  1498. }
  1499.  
  1500. public:
  1501. typedef _Result result_type;
  1502.  
  1503. template<typename... _Args>
  1504. explicit _Bind_result(const _Functor& __f, _Args&&... __args)
  1505. : _M_f(__f), _M_bound_args(std::forward<_Args>(__args)...)
  1506. { }
  1507.  
  1508. template<typename... _Args>
  1509. explicit _Bind_result(_Functor&& __f, _Args&&... __args)
  1510. : _M_f(std::move(__f)), _M_bound_args(std::forward<_Args>(__args)...)
  1511. { }
  1512.  
  1513. _Bind_result(const _Bind_result&) = default;
  1514.  
  1515. _Bind_result(_Bind_result&& __b)
  1516. : _M_f(std::move(__b._M_f)), _M_bound_args(std::move(__b._M_bound_args))
  1517. { }
  1518.  
  1519. // Call unqualified
  1520. template<typename... _Args>
  1521. result_type
  1522. operator()(_Args&&... __args)
  1523. {
  1524. return this->__call<_Result>(
  1525. std::forward_as_tuple(std::forward<_Args>(__args)...),
  1526. _Bound_indexes());
  1527. }
  1528.  
  1529. // Call as const
  1530. template<typename... _Args>
  1531. result_type
  1532. operator()(_Args&&... __args) const
  1533. {
  1534. return this->__call<_Result>(
  1535. std::forward_as_tuple(std::forward<_Args>(__args)...),
  1536. _Bound_indexes());
  1537. }
  1538.  
  1539. // Call as volatile
  1540. template<typename... _Args>
  1541. result_type
  1542. operator()(_Args&&... __args) volatile
  1543. {
  1544. return this->__call<_Result>(
  1545. std::forward_as_tuple(std::forward<_Args>(__args)...),
  1546. _Bound_indexes());
  1547. }
  1548.  
  1549. // Call as const volatile
  1550. template<typename... _Args>
  1551. result_type
  1552. operator()(_Args&&... __args) const volatile
  1553. {
  1554. return this->__call<_Result>(
  1555. std::forward_as_tuple(std::forward<_Args>(__args)...),
  1556. _Bound_indexes());
  1557. }
  1558. };
  1559.  
  1560. /**
  1561. * @brief Class template _Bind is always a bind expression.
  1562. * @ingroup binders
  1563. */
  1564. template<typename _Signature>
  1565. struct is_bind_expression<_Bind<_Signature> >
  1566. : public true_type { };
  1567.  
  1568. /**
  1569. * @brief Class template _Bind is always a bind expression.
  1570. * @ingroup binders
  1571. */
  1572. template<typename _Signature>
  1573. struct is_bind_expression<const _Bind<_Signature> >
  1574. : public true_type { };
  1575.  
  1576. /**
  1577. * @brief Class template _Bind is always a bind expression.
  1578. * @ingroup binders
  1579. */
  1580. template<typename _Signature>
  1581. struct is_bind_expression<volatile _Bind<_Signature> >
  1582. : public true_type { };
  1583.  
  1584. /**
  1585. * @brief Class template _Bind is always a bind expression.
  1586. * @ingroup binders
  1587. */
  1588. template<typename _Signature>
  1589. struct is_bind_expression<const volatile _Bind<_Signature>>
  1590. : public true_type { };
  1591.  
  1592. /**
  1593. * @brief Class template _Bind_result is always a bind expression.
  1594. * @ingroup binders
  1595. */
  1596. template<typename _Result, typename _Signature>
  1597. struct is_bind_expression<_Bind_result<_Result, _Signature>>
  1598. : public true_type { };
  1599.  
  1600. /**
  1601. * @brief Class template _Bind_result is always a bind expression.
  1602. * @ingroup binders
  1603. */
  1604. template<typename _Result, typename _Signature>
  1605. struct is_bind_expression<const _Bind_result<_Result, _Signature>>
  1606. : public true_type { };
  1607.  
  1608. /**
  1609. * @brief Class template _Bind_result is always a bind expression.
  1610. * @ingroup binders
  1611. */
  1612. template<typename _Result, typename _Signature>
  1613. struct is_bind_expression<volatile _Bind_result<_Result, _Signature>>
  1614. : public true_type { };
  1615.  
  1616. /**
  1617. * @brief Class template _Bind_result is always a bind expression.
  1618. * @ingroup binders
  1619. */
  1620. template<typename _Result, typename _Signature>
  1621. struct is_bind_expression<const volatile _Bind_result<_Result, _Signature>>
  1622. : public true_type { };
  1623.  
  1624. // Trait type used to remove std::bind() from overload set via SFINAE
  1625. // when first argument has integer type, so that std::bind() will
  1626. // not be a better match than ::bind() from the BSD Sockets API.
  1627. template<typename _Tp, typename _Tp2 = typename decay<_Tp>::type>
  1628. using __is_socketlike = __or_<is_integral<_Tp2>, is_enum<_Tp2>>;
  1629.  
  1630. template<bool _SocketLike, typename _Func, typename... _BoundArgs>
  1631. struct _Bind_helper
  1632. {
  1633. typedef _Maybe_wrap_member_pointer<typename decay<_Func>::type>
  1634. __maybe_type;
  1635. typedef typename __maybe_type::type __func_type;
  1636. typedef _Bind<__func_type(typename decay<_BoundArgs>::type...)> type;
  1637. };
  1638.  
  1639. // Partial specialization for is_socketlike == true, does not define
  1640. // nested type so std::bind() will not participate in overload resolution
  1641. // when the first argument might be a socket file descriptor.
  1642. template<typename _Func, typename... _BoundArgs>
  1643. struct _Bind_helper<true, _Func, _BoundArgs...>
  1644. { };
  1645.  
  1646. /**
  1647. * @brief Function template for std::bind.
  1648. * @ingroup binders
  1649. */
  1650. template<typename _Func, typename... _BoundArgs>
  1651. inline typename
  1652. _Bind_helper<__is_socketlike<_Func>::value, _Func, _BoundArgs...>::type
  1653. bind(_Func&& __f, _BoundArgs&&... __args)
  1654. {
  1655. typedef _Bind_helper<false, _Func, _BoundArgs...> __helper_type;
  1656. typedef typename __helper_type::__maybe_type __maybe_type;
  1657. typedef typename __helper_type::type __result_type;
  1658. return __result_type(__maybe_type::__do_wrap(std::forward<_Func>(__f)),
  1659. std::forward<_BoundArgs>(__args)...);
  1660. }
  1661.  
  1662. template<typename _Result, typename _Func, typename... _BoundArgs>
  1663. struct _Bindres_helper
  1664. {
  1665. typedef _Maybe_wrap_member_pointer<typename decay<_Func>::type>
  1666. __maybe_type;
  1667. typedef typename __maybe_type::type __functor_type;
  1668. typedef _Bind_result<_Result,
  1669. __functor_type(typename decay<_BoundArgs>::type...)>
  1670. type;
  1671. };
  1672.  
  1673. /**
  1674. * @brief Function template for std::bind<R>.
  1675. * @ingroup binders
  1676. */
  1677. template<typename _Result, typename _Func, typename... _BoundArgs>
  1678. inline
  1679. typename _Bindres_helper<_Result, _Func, _BoundArgs...>::type
  1680. bind(_Func&& __f, _BoundArgs&&... __args)
  1681. {
  1682. typedef _Bindres_helper<_Result, _Func, _BoundArgs...> __helper_type;
  1683. typedef typename __helper_type::__maybe_type __maybe_type;
  1684. typedef typename __helper_type::type __result_type;
  1685. return __result_type(__maybe_type::__do_wrap(std::forward<_Func>(__f)),
  1686. std::forward<_BoundArgs>(__args)...);
  1687. }
  1688.  
  1689. template<typename _Signature>
  1690. struct _Bind_simple;
  1691.  
  1692. template<typename _Callable, typename... _Args>
  1693. struct _Bind_simple<_Callable(_Args...)>
  1694. {
  1695. typedef typename result_of<_Callable(_Args...)>::type result_type;
  1696.  
  1697. template<typename... _Args2, typename = typename
  1698. enable_if< sizeof...(_Args) == sizeof...(_Args2)>::type>
  1699. explicit
  1700. _Bind_simple(const _Callable& __callable, _Args2&&... __args)
  1701. : _M_bound(__callable, std::forward<_Args2>(__args)...)
  1702. { }
  1703.  
  1704. template<typename... _Args2, typename = typename
  1705. enable_if< sizeof...(_Args) == sizeof...(_Args2)>::type>
  1706. explicit
  1707. _Bind_simple(_Callable&& __callable, _Args2&&... __args)
  1708. : _M_bound(std::move(__callable), std::forward<_Args2>(__args)...)
  1709. { }
  1710.  
  1711. _Bind_simple(const _Bind_simple&) = default;
  1712. _Bind_simple(_Bind_simple&&) = default;
  1713.  
  1714. result_type
  1715. operator()()
  1716. {
  1717. typedef typename _Build_index_tuple<sizeof...(_Args)>::__type _Indices;
  1718. return _M_invoke(_Indices());
  1719. }
  1720.  
  1721. private:
  1722.  
  1723. template<std::size_t... _Indices>
  1724. typename result_of<_Callable(_Args...)>::type
  1725. _M_invoke(_Index_tuple<_Indices...>)
  1726. {
  1727. // std::bind always forwards bound arguments as lvalues,
  1728. // but this type can call functions which only accept rvalues.
  1729. return std::forward<_Callable>(std::get<>(_M_bound))(
  1730. std::forward<_Args>(std::get<_Indices+>(_M_bound))...);
  1731. }
  1732.  
  1733. std::tuple<_Callable, _Args...> _M_bound;
  1734. };
  1735.  
  1736. template<typename _Func, typename... _BoundArgs>
  1737. struct _Bind_simple_helper
  1738. {
  1739. typedef _Maybe_wrap_member_pointer<typename decay<_Func>::type>
  1740. __maybe_type;
  1741. typedef typename __maybe_type::type __func_type;
  1742. typedef _Bind_simple<__func_type(typename decay<_BoundArgs>::type...)>
  1743. __type;
  1744. };
  1745.  
  1746. // Simplified version of std::bind for internal use, without support for
  1747. // unbound arguments, placeholders or nested bind expressions.
  1748. template<typename _Callable, typename... _Args>
  1749. typename _Bind_simple_helper<_Callable, _Args...>::__type
  1750. __bind_simple(_Callable&& __callable, _Args&&... __args)
  1751. {
  1752. typedef _Bind_simple_helper<_Callable, _Args...> __helper_type;
  1753. typedef typename __helper_type::__maybe_type __maybe_type;
  1754. typedef typename __helper_type::__type __result_type;
  1755. return __result_type(
  1756. __maybe_type::__do_wrap( std::forward<_Callable>(__callable)),
  1757. std::forward<_Args>(__args)...);
  1758. }
  1759.  
  1760. /**
  1761. * @brief Exception class thrown when class template function's
  1762. * operator() is called with an empty target.
  1763. * @ingroup exceptions
  1764. */
  1765. class bad_function_call : public std::exception
  1766. {
  1767. public:
  1768. virtual ~bad_function_call() noexcept;
  1769.  
  1770. const char* what() const noexcept;
  1771. };
  1772.  
  1773. /**
  1774. * Trait identifying "location-invariant" types, meaning that the
  1775. * address of the object (or any of its members) will not escape.
  1776. * Also implies a trivial copy constructor and assignment operator.
  1777. */
  1778. template<typename _Tp>
  1779. struct __is_location_invariant
  1780. : integral_constant<bool, (is_pointer<_Tp>::value
  1781. || is_member_pointer<_Tp>::value)>
  1782. { };
  1783.  
  1784. class _Undefined_class;
  1785.  
  1786. union _Nocopy_types
  1787. {
  1788. void* _M_object;
  1789. const void* _M_const_object;
  1790. void (*_M_function_pointer)();
  1791. void (_Undefined_class::*_M_member_pointer)();
  1792. };
  1793.  
  1794. union _Any_data
  1795. {
  1796. void* _M_access() { return &_M_pod_data[]; }
  1797. const void* _M_access() const { return &_M_pod_data[]; }
  1798.  
  1799. template<typename _Tp>
  1800. _Tp&
  1801. _M_access()
  1802. { return *static_cast<_Tp*>(_M_access()); }
  1803.  
  1804. template<typename _Tp>
  1805. const _Tp&
  1806. _M_access() const
  1807. { return *static_cast<const _Tp*>(_M_access()); }
  1808.  
  1809. _Nocopy_types _M_unused;
  1810. char _M_pod_data[sizeof(_Nocopy_types)];
  1811. };
  1812.  
  1813. enum _Manager_operation
  1814. {
  1815. __get_type_info,
  1816. __get_functor_ptr,
  1817. __clone_functor,
  1818. __destroy_functor
  1819. };
  1820.  
  1821. // Simple type wrapper that helps avoid annoying const problems
  1822. // when casting between void pointers and pointers-to-pointers.
  1823. template<typename _Tp>
  1824. struct _Simple_type_wrapper
  1825. {
  1826. _Simple_type_wrapper(_Tp __value) : __value(__value) { }
  1827.  
  1828. _Tp __value;
  1829. };
  1830.  
  1831. template<typename _Tp>
  1832. struct __is_location_invariant<_Simple_type_wrapper<_Tp> >
  1833. : __is_location_invariant<_Tp>
  1834. { };
  1835.  
  1836. // Converts a reference to a function object into a callable
  1837. // function object.
  1838. template<typename _Functor>
  1839. inline _Functor&
  1840. __callable_functor(_Functor& __f)
  1841. { return __f; }
  1842.  
  1843. template<typename _Member, typename _Class>
  1844. inline _Mem_fn<_Member _Class::*>
  1845. __callable_functor(_Member _Class::* &__p)
  1846. { return std::mem_fn(__p); }
  1847.  
  1848. template<typename _Member, typename _Class>
  1849. inline _Mem_fn<_Member _Class::*>
  1850. __callable_functor(_Member _Class::* const &__p)
  1851. { return std::mem_fn(__p); }
  1852.  
  1853. template<typename _Member, typename _Class>
  1854. inline _Mem_fn<_Member _Class::*>
  1855. __callable_functor(_Member _Class::* volatile &__p)
  1856. { return std::mem_fn(__p); }
  1857.  
  1858. template<typename _Member, typename _Class>
  1859. inline _Mem_fn<_Member _Class::*>
  1860. __callable_functor(_Member _Class::* const volatile &__p)
  1861. { return std::mem_fn(__p); }
  1862.  
  1863. template<typename _Signature>
  1864. class function;
  1865.  
  1866. /// Base class of all polymorphic function object wrappers.
  1867. class _Function_base
  1868. {
  1869. public:
  1870. static const std::size_t _M_max_size = sizeof(_Nocopy_types);
  1871. static const std::size_t _M_max_align = __alignof__(_Nocopy_types);
  1872.  
  1873. template<typename _Functor>
  1874. class _Base_manager
  1875. {
  1876. protected:
  1877. static const bool __stored_locally =
  1878. (__is_location_invariant<_Functor>::value
  1879. && sizeof(_Functor) <= _M_max_size
  1880. && __alignof__(_Functor) <= _M_max_align
  1881. && (_M_max_align % __alignof__(_Functor) == ));
  1882.  
  1883. typedef integral_constant<bool, __stored_locally> _Local_storage;
  1884.  
  1885. // Retrieve a pointer to the function object
  1886. static _Functor*
  1887. _M_get_pointer(const _Any_data& __source)
  1888. {
  1889. const _Functor* __ptr =
  1890. __stored_locally? std::__addressof(__source._M_access<_Functor>())
  1891. /* have stored a pointer */ : __source._M_access<_Functor*>();
  1892. return const_cast<_Functor*>(__ptr);
  1893. }
  1894.  
  1895. // Clone a location-invariant function object that fits within
  1896. // an _Any_data structure.
  1897. static void
  1898. _M_clone(_Any_data& __dest, const _Any_data& __source, true_type)
  1899. {
  1900. new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
  1901. }
  1902.  
  1903. // Clone a function object that is not location-invariant or
  1904. // that cannot fit into an _Any_data structure.
  1905. static void
  1906. _M_clone(_Any_data& __dest, const _Any_data& __source, false_type)
  1907. {
  1908. __dest._M_access<_Functor*>() =
  1909. new _Functor(*__source._M_access<_Functor*>());
  1910. }
  1911.  
  1912. // Destroying a location-invariant object may still require
  1913. // destruction.
  1914. static void
  1915. _M_destroy(_Any_data& __victim, true_type)
  1916. {
  1917. __victim._M_access<_Functor>().~_Functor();
  1918. }
  1919.  
  1920. // Destroying an object located on the heap.
  1921. static void
  1922. _M_destroy(_Any_data& __victim, false_type)
  1923. {
  1924. delete __victim._M_access<_Functor*>();
  1925. }
  1926.  
  1927. public:
  1928. static bool
  1929. _M_manager(_Any_data& __dest, const _Any_data& __source,
  1930. _Manager_operation __op)
  1931. {
  1932. switch (__op)
  1933. {
  1934. #ifdef __GXX_RTTI
  1935. case __get_type_info:
  1936. __dest._M_access<const type_info*>() = &typeid(_Functor);
  1937. break;
  1938. #endif
  1939. case __get_functor_ptr:
  1940. __dest._M_access<_Functor*>() = _M_get_pointer(__source);
  1941. break;
  1942.  
  1943. case __clone_functor:
  1944. _M_clone(__dest, __source, _Local_storage());
  1945. break;
  1946.  
  1947. case __destroy_functor:
  1948. _M_destroy(__dest, _Local_storage());
  1949. break;
  1950. }
  1951. return false;
  1952. }
  1953.  
  1954. static void
  1955. _M_init_functor(_Any_data& __functor, _Functor&& __f)
  1956. { _M_init_functor(__functor, std::move(__f), _Local_storage()); }
  1957.  
  1958. template<typename _Signature>
  1959. static bool
  1960. _M_not_empty_function(const function<_Signature>& __f)
  1961. { return static_cast<bool>(__f); }
  1962.  
  1963. template<typename _Tp>
  1964. static bool
  1965. _M_not_empty_function(const _Tp*& __fp)
  1966. { return __fp; }
  1967.  
  1968. template<typename _Class, typename _Tp>
  1969. static bool
  1970. _M_not_empty_function(_Tp _Class::* const& __mp)
  1971. { return __mp; }
  1972.  
  1973. template<typename _Tp>
  1974. static bool
  1975. _M_not_empty_function(const _Tp&)
  1976. { return true; }
  1977.  
  1978. private:
  1979. static void
  1980. _M_init_functor(_Any_data& __functor, _Functor&& __f, true_type)
  1981. { new (__functor._M_access()) _Functor(std::move(__f)); }
  1982.  
  1983. static void
  1984. _M_init_functor(_Any_data& __functor, _Functor&& __f, false_type)
  1985. { __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); }
  1986. };
  1987.  
  1988. template<typename _Functor>
  1989. class _Ref_manager : public _Base_manager<_Functor*>
  1990. {
  1991. typedef _Function_base::_Base_manager<_Functor*> _Base;
  1992.  
  1993. public:
  1994. static bool
  1995. _M_manager(_Any_data& __dest, const _Any_data& __source,
  1996. _Manager_operation __op)
  1997. {
  1998. switch (__op)
  1999. {
  2000. #ifdef __GXX_RTTI
  2001. case __get_type_info:
  2002. __dest._M_access<const type_info*>() = &typeid(_Functor);
  2003. break;
  2004. #endif
  2005. case __get_functor_ptr:
  2006. __dest._M_access<_Functor*>() = *_Base::_M_get_pointer(__source);
  2007. return is_const<_Functor>::value;
  2008. break;
  2009.  
  2010. default:
  2011. _Base::_M_manager(__dest, __source, __op);
  2012. }
  2013. return false;
  2014. }
  2015.  
  2016. static void
  2017. _M_init_functor(_Any_data& __functor, reference_wrapper<_Functor> __f)
  2018. {
  2019. _Base::_M_init_functor(__functor, std::__addressof(__f.get()));
  2020. }
  2021. };
  2022.  
  2023. _Function_base() : _M_manager() { }
  2024.  
  2025. ~_Function_base()
  2026. {
  2027. if (_M_manager)
  2028. _M_manager(_M_functor, _M_functor, __destroy_functor);
  2029. }
  2030.  
  2031. bool _M_empty() const { return !_M_manager; }
  2032.  
  2033. typedef bool (*_Manager_type)(_Any_data&, const _Any_data&,
  2034. _Manager_operation);
  2035.  
  2036. _Any_data _M_functor;
  2037. _Manager_type _M_manager;
  2038. };
  2039.  
  2040. template<typename _Signature, typename _Functor>
  2041. class _Function_handler;
  2042.  
  2043. template<typename _Res, typename _Functor, typename... _ArgTypes>
  2044. class _Function_handler<_Res(_ArgTypes...), _Functor>
  2045. : public _Function_base::_Base_manager<_Functor>
  2046. {
  2047. typedef _Function_base::_Base_manager<_Functor> _Base;
  2048.  
  2049. public:
  2050. static _Res
  2051. _M_invoke(const _Any_data& __functor, _ArgTypes... __args)
  2052. {
  2053. return (*_Base::_M_get_pointer(__functor))(
  2054. std::forward<_ArgTypes>(__args)...);
  2055. }
  2056. };
  2057.  
  2058. template<typename _Functor, typename... _ArgTypes>
  2059. class _Function_handler<void(_ArgTypes...), _Functor>
  2060. : public _Function_base::_Base_manager<_Functor>
  2061. {
  2062. typedef _Function_base::_Base_manager<_Functor> _Base;
  2063.  
  2064. public:
  2065. static void
  2066. _M_invoke(const _Any_data& __functor, _ArgTypes... __args)
  2067. {
  2068. (*_Base::_M_get_pointer(__functor))(
  2069. std::forward<_ArgTypes>(__args)...);
  2070. }
  2071. };
  2072.  
  2073. template<typename _Res, typename _Functor, typename... _ArgTypes>
  2074. class _Function_handler<_Res(_ArgTypes...), reference_wrapper<_Functor> >
  2075. : public _Function_base::_Ref_manager<_Functor>
  2076. {
  2077. typedef _Function_base::_Ref_manager<_Functor> _Base;
  2078.  
  2079. public:
  2080. static _Res
  2081. _M_invoke(const _Any_data& __functor, _ArgTypes... __args)
  2082. {
  2083. return __callable_functor(**_Base::_M_get_pointer(__functor))(
  2084. std::forward<_ArgTypes>(__args)...);
  2085. }
  2086. };
  2087.  
  2088. template<typename _Functor, typename... _ArgTypes>
  2089. class _Function_handler<void(_ArgTypes...), reference_wrapper<_Functor> >
  2090. : public _Function_base::_Ref_manager<_Functor>
  2091. {
  2092. typedef _Function_base::_Ref_manager<_Functor> _Base;
  2093.  
  2094. public:
  2095. static void
  2096. _M_invoke(const _Any_data& __functor, _ArgTypes... __args)
  2097. {
  2098. __callable_functor(**_Base::_M_get_pointer(__functor))(
  2099. std::forward<_ArgTypes>(__args)...);
  2100. }
  2101. };
  2102.  
  2103. template<typename _Class, typename _Member, typename _Res,
  2104. typename... _ArgTypes>
  2105. class _Function_handler<_Res(_ArgTypes...), _Member _Class::*>
  2106. : public _Function_handler<void(_ArgTypes...), _Member _Class::*>
  2107. {
  2108. typedef _Function_handler<void(_ArgTypes...), _Member _Class::*>
  2109. _Base;
  2110.  
  2111. public:
  2112. static _Res
  2113. _M_invoke(const _Any_data& __functor, _ArgTypes... __args)
  2114. {
  2115. return std::mem_fn(_Base::_M_get_pointer(__functor)->__value)(
  2116. std::forward<_ArgTypes>(__args)...);
  2117. }
  2118. };
  2119.  
  2120. template<typename _Class, typename _Member, typename... _ArgTypes>
  2121. class _Function_handler<void(_ArgTypes...), _Member _Class::*>
  2122. : public _Function_base::_Base_manager<
  2123. _Simple_type_wrapper< _Member _Class::* > >
  2124. {
  2125. typedef _Member _Class::* _Functor;
  2126. typedef _Simple_type_wrapper<_Functor> _Wrapper;
  2127. typedef _Function_base::_Base_manager<_Wrapper> _Base;
  2128.  
  2129. public:
  2130. static bool
  2131. _M_manager(_Any_data& __dest, const _Any_data& __source,
  2132. _Manager_operation __op)
  2133. {
  2134. switch (__op)
  2135. {
  2136. #ifdef __GXX_RTTI
  2137. case __get_type_info:
  2138. __dest._M_access<const type_info*>() = &typeid(_Functor);
  2139. break;
  2140. #endif
  2141. case __get_functor_ptr:
  2142. __dest._M_access<_Functor*>() =
  2143. &_Base::_M_get_pointer(__source)->__value;
  2144. break;
  2145.  
  2146. default:
  2147. _Base::_M_manager(__dest, __source, __op);
  2148. }
  2149. return false;
  2150. }
  2151.  
  2152. static void
  2153. _M_invoke(const _Any_data& __functor, _ArgTypes... __args)
  2154. {
  2155. std::mem_fn(_Base::_M_get_pointer(__functor)->__value)(
  2156. std::forward<_ArgTypes>(__args)...);
  2157. }
  2158. };
  2159.  
  2160. /**
  2161. * @brief Primary class template for std::function.
  2162. * @ingroup functors
  2163. *
  2164. * Polymorphic function wrapper.
  2165. */
  2166. template<typename _Res, typename... _ArgTypes>
  2167. class function<_Res(_ArgTypes...)>
  2168. : public _Maybe_unary_or_binary_function<_Res, _ArgTypes...>,
  2169. private _Function_base
  2170. {
  2171. typedef _Res _Signature_type(_ArgTypes...);
  2172.  
  2173. template<typename _Functor>
  2174. using _Invoke = decltype(__callable_functor(std::declval<_Functor&>())
  2175. (std::declval<_ArgTypes>()...) );
  2176.  
  2177. template<typename _CallRes, typename _Res1>
  2178. struct _CheckResult
  2179. : is_convertible<_CallRes, _Res1> { };
  2180.  
  2181. template<typename _CallRes>
  2182. struct _CheckResult<_CallRes, void>
  2183. : true_type { };
  2184.  
  2185. template<typename _Functor>
  2186. using _Callable = _CheckResult<_Invoke<_Functor>, _Res>;
  2187.  
  2188. template<typename _Cond, typename _Tp>
  2189. using _Requires = typename enable_if<_Cond::value, _Tp>::type;
  2190.  
  2191. public:
  2192. typedef _Res result_type;
  2193.  
  2194. // [3.7.2.1] construct/copy/destroy
  2195.  
  2196. /**
  2197. * @brief Default construct creates an empty function call wrapper.
  2198. * @post @c !(bool)*this
  2199. */
  2200. function() noexcept
  2201. : _Function_base() { }
  2202.  
  2203. /**
  2204. * @brief Creates an empty function call wrapper.
  2205. * @post @c !(bool)*this
  2206. */
  2207. function(nullptr_t) noexcept
  2208. : _Function_base() { }
  2209.  
  2210. /**
  2211. * @brief %Function copy constructor.
  2212. * @param __x A %function object with identical call signature.
  2213. * @post @c bool(*this) == bool(__x)
  2214. *
  2215. * The newly-created %function contains a copy of the target of @a
  2216. * __x (if it has one).
  2217. */
  2218. function(const function& __x);
  2219.  
  2220. /**
  2221. * @brief %Function move constructor.
  2222. * @param __x A %function object rvalue with identical call signature.
  2223. *
  2224. * The newly-created %function contains the target of @a __x
  2225. * (if it has one).
  2226. */
  2227. function(function&& __x) : _Function_base()
  2228. {
  2229. __x.swap(*this);
  2230. }
  2231.  
  2232. // TODO: needs allocator_arg_t
  2233.  
  2234. /**
  2235. * @brief Builds a %function that targets a copy of the incoming
  2236. * function object.
  2237. * @param __f A %function object that is callable with parameters of
  2238. * type @c T1, @c T2, ..., @c TN and returns a value convertible
  2239. * to @c Res.
  2240. *
  2241. * The newly-created %function object will target a copy of
  2242. * @a __f. If @a __f is @c reference_wrapper<F>, then this function
  2243. * object will contain a reference to the function object @c
  2244. * __f.get(). If @a __f is a NULL function pointer or NULL
  2245. * pointer-to-member, the newly-created object will be empty.
  2246. *
  2247. * If @a __f is a non-NULL function pointer or an object of type @c
  2248. * reference_wrapper<F>, this function will not throw.
  2249. */
  2250. template<typename _Functor,
  2251. typename = _Requires<_Callable<_Functor>, void>>
  2252. function(_Functor);
  2253.  
  2254. /**
  2255. * @brief %Function assignment operator.
  2256. * @param __x A %function with identical call signature.
  2257. * @post @c (bool)*this == (bool)x
  2258. * @returns @c *this
  2259. *
  2260. * The target of @a __x is copied to @c *this. If @a __x has no
  2261. * target, then @c *this will be empty.
  2262. *
  2263. * If @a __x targets a function pointer or a reference to a function
  2264. * object, then this operation will not throw an %exception.
  2265. */
  2266. function&
  2267. operator=(const function& __x)
  2268. {
  2269. function(__x).swap(*this);
  2270. return *this;
  2271. }
  2272.  
  2273. /**
  2274. * @brief %Function move-assignment operator.
  2275. * @param __x A %function rvalue with identical call signature.
  2276. * @returns @c *this
  2277. *
  2278. * The target of @a __x is moved to @c *this. If @a __x has no
  2279. * target, then @c *this will be empty.
  2280. *
  2281. * If @a __x targets a function pointer or a reference to a function
  2282. * object, then this operation will not throw an %exception.
  2283. */
  2284. function&
  2285. operator=(function&& __x)
  2286. {
  2287. function(std::move(__x)).swap(*this);
  2288. return *this;
  2289. }
  2290.  
  2291. /**
  2292. * @brief %Function assignment to zero.
  2293. * @post @c !(bool)*this
  2294. * @returns @c *this
  2295. *
  2296. * The target of @c *this is deallocated, leaving it empty.
  2297. */
  2298. function&
  2299. operator=(nullptr_t)
  2300. {
  2301. if (_M_manager)
  2302. {
  2303. _M_manager(_M_functor, _M_functor, __destroy_functor);
  2304. _M_manager = ;
  2305. _M_invoker = ;
  2306. }
  2307. return *this;
  2308. }
  2309.  
  2310. /**
  2311. * @brief %Function assignment to a new target.
  2312. * @param __f A %function object that is callable with parameters of
  2313. * type @c T1, @c T2, ..., @c TN and returns a value convertible
  2314. * to @c Res.
  2315. * @return @c *this
  2316. *
  2317. * This %function object wrapper will target a copy of @a
  2318. * __f. If @a __f is @c reference_wrapper<F>, then this function
  2319. * object will contain a reference to the function object @c
  2320. * __f.get(). If @a __f is a NULL function pointer or NULL
  2321. * pointer-to-member, @c this object will be empty.
  2322. *
  2323. * If @a __f is a non-NULL function pointer or an object of type @c
  2324. * reference_wrapper<F>, this function will not throw.
  2325. */
  2326. template<typename _Functor>
  2327. _Requires<_Callable<_Functor>, function&>
  2328. operator=(_Functor&& __f)
  2329. {
  2330. function(std::forward<_Functor>(__f)).swap(*this);
  2331. return *this;
  2332. }
  2333.  
  2334. /// @overload
  2335. template<typename _Functor>
  2336. function&
  2337. operator=(reference_wrapper<_Functor> __f) noexcept
  2338. {
  2339. function(__f).swap(*this);
  2340. return *this;
  2341. }
  2342.  
  2343. // [3.7.2.2] function modifiers
  2344.  
  2345. /**
  2346. * @brief Swap the targets of two %function objects.
  2347. * @param __x A %function with identical call signature.
  2348. *
  2349. * Swap the targets of @c this function object and @a __f. This
  2350. * function will not throw an %exception.
  2351. */
  2352. void swap(function& __x)
  2353. {
  2354. std::swap(_M_functor, __x._M_functor);
  2355. std::swap(_M_manager, __x._M_manager);
  2356. std::swap(_M_invoker, __x._M_invoker);
  2357. }
  2358.  
  2359. // TODO: needs allocator_arg_t
  2360. /*
  2361. template<typename _Functor, typename _Alloc>
  2362. void
  2363. assign(_Functor&& __f, const _Alloc& __a)
  2364. {
  2365. function(allocator_arg, __a,
  2366. std::forward<_Functor>(__f)).swap(*this);
  2367. }
  2368. */
  2369.  
  2370. // [3.7.2.3] function capacity
  2371.  
  2372. /**
  2373. * @brief Determine if the %function wrapper has a target.
  2374. *
  2375. * @return @c true when this %function object contains a target,
  2376. * or @c false when it is empty.
  2377. *
  2378. * This function will not throw an %exception.
  2379. */
  2380. explicit operator bool() const noexcept
  2381. { return !_M_empty(); }
  2382.  
  2383. // [3.7.2.4] function invocation
  2384.  
  2385. /**
  2386. * @brief Invokes the function targeted by @c *this.
  2387. * @returns the result of the target.
  2388. * @throws bad_function_call when @c !(bool)*this
  2389. *
  2390. * The function call operator invokes the target function object
  2391. * stored by @c this.
  2392. */
  2393. _Res operator()(_ArgTypes... __args) const;
  2394.  
  2395. #ifdef __GXX_RTTI
  2396. // [3.7.2.5] function target access
  2397. /**
  2398. * @brief Determine the type of the target of this function object
  2399. * wrapper.
  2400. *
  2401. * @returns the type identifier of the target function object, or
  2402. * @c typeid(void) if @c !(bool)*this.
  2403. *
  2404. * This function will not throw an %exception.
  2405. */
  2406. const type_info& target_type() const noexcept;
  2407.  
  2408. /**
  2409. * @brief Access the stored target function object.
  2410. *
  2411. * @return Returns a pointer to the stored target function object,
  2412. * if @c typeid(Functor).equals(target_type()); otherwise, a NULL
  2413. * pointer.
  2414. *
  2415. * This function will not throw an %exception.
  2416. */
  2417. template<typename _Functor> _Functor* target() noexcept;
  2418.  
  2419. /// @overload
  2420. template<typename _Functor> const _Functor* target() const noexcept;
  2421. #endif
  2422.  
  2423. private:
  2424. typedef _Res (*_Invoker_type)(const _Any_data&, _ArgTypes...);
  2425. _Invoker_type _M_invoker;
  2426. };
  2427.  
  2428. // Out-of-line member definitions.
  2429. template<typename _Res, typename... _ArgTypes>
  2430. function<_Res(_ArgTypes...)>::
  2431. function(const function& __x)
  2432. : _Function_base()
  2433. {
  2434. if (static_cast<bool>(__x))
  2435. {
  2436. _M_invoker = __x._M_invoker;
  2437. _M_manager = __x._M_manager;
  2438. __x._M_manager(_M_functor, __x._M_functor, __clone_functor);
  2439. }
  2440. }
  2441.  
  2442. template<typename _Res, typename... _ArgTypes>
  2443. template<typename _Functor, typename>
  2444. function<_Res(_ArgTypes...)>::
  2445. function(_Functor __f)
  2446. : _Function_base()
  2447. {
  2448. typedef _Function_handler<_Signature_type, _Functor> _My_handler;
  2449.  
  2450. if (_My_handler::_M_not_empty_function(__f))
  2451. {
  2452. _My_handler::_M_init_functor(_M_functor, std::move(__f));
  2453. _M_invoker = &_My_handler::_M_invoke;
  2454. _M_manager = &_My_handler::_M_manager;
  2455. }
  2456. }
  2457.  
  2458. template<typename _Res, typename... _ArgTypes>
  2459. _Res
  2460. function<_Res(_ArgTypes...)>::
  2461. operator()(_ArgTypes... __args) const
  2462. {
  2463. if (_M_empty())
  2464. __throw_bad_function_call();
  2465. return _M_invoker(_M_functor, std::forward<_ArgTypes>(__args)...);
  2466. }
  2467.  
  2468. #ifdef __GXX_RTTI
  2469. template<typename _Res, typename... _ArgTypes>
  2470. const type_info&
  2471. function<_Res(_ArgTypes...)>::
  2472. target_type() const noexcept
  2473. {
  2474. if (_M_manager)
  2475. {
  2476. _Any_data __typeinfo_result;
  2477. _M_manager(__typeinfo_result, _M_functor, __get_type_info);
  2478. return *__typeinfo_result._M_access<const type_info*>();
  2479. }
  2480. else
  2481. return typeid(void);
  2482. }
  2483.  
  2484. template<typename _Res, typename... _ArgTypes>
  2485. template<typename _Functor>
  2486. _Functor*
  2487. function<_Res(_ArgTypes...)>::
  2488. target() noexcept
  2489. {
  2490. if (typeid(_Functor) == target_type() && _M_manager)
  2491. {
  2492. _Any_data __ptr;
  2493. if (_M_manager(__ptr, _M_functor, __get_functor_ptr)
  2494. && !is_const<_Functor>::value)
  2495. return ;
  2496. else
  2497. return __ptr._M_access<_Functor*>();
  2498. }
  2499. else
  2500. return ;
  2501. }
  2502.  
  2503. template<typename _Res, typename... _ArgTypes>
  2504. template<typename _Functor>
  2505. const _Functor*
  2506. function<_Res(_ArgTypes...)>::
  2507. target() const noexcept
  2508. {
  2509. if (typeid(_Functor) == target_type() && _M_manager)
  2510. {
  2511. _Any_data __ptr;
  2512. _M_manager(__ptr, _M_functor, __get_functor_ptr);
  2513. return __ptr._M_access<const _Functor*>();
  2514. }
  2515. else
  2516. return ;
  2517. }
  2518. #endif
  2519.  
  2520. // [20.7.15.2.6] null pointer comparisons
  2521.  
  2522. /**
  2523. * @brief Compares a polymorphic function object wrapper against 0
  2524. * (the NULL pointer).
  2525. * @returns @c true if the wrapper has no target, @c false otherwise
  2526. *
  2527. * This function will not throw an %exception.
  2528. */
  2529. template<typename _Res, typename... _Args>
  2530. inline bool
  2531. operator==(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
  2532. { return !static_cast<bool>(__f); }
  2533.  
  2534. /// @overload
  2535. template<typename _Res, typename... _Args>
  2536. inline bool
  2537. operator==(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
  2538. { return !static_cast<bool>(__f); }
  2539.  
  2540. /**
  2541. * @brief Compares a polymorphic function object wrapper against 0
  2542. * (the NULL pointer).
  2543. * @returns @c false if the wrapper has no target, @c true otherwise
  2544. *
  2545. * This function will not throw an %exception.
  2546. */
  2547. template<typename _Res, typename... _Args>
  2548. inline bool
  2549. operator!=(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
  2550. { return static_cast<bool>(__f); }
  2551.  
  2552. /// @overload
  2553. template<typename _Res, typename... _Args>
  2554. inline bool
  2555. operator!=(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
  2556. { return static_cast<bool>(__f); }
  2557.  
  2558. // [20.7.15.2.7] specialized algorithms
  2559.  
  2560. /**
  2561. * @brief Swap the targets of two polymorphic function object wrappers.
  2562. *
  2563. * This function will not throw an %exception.
  2564. */
  2565. template<typename _Res, typename... _Args>
  2566. inline void
  2567. swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y)
  2568. { __x.swap(__y); }
  2569.  
  2570. _GLIBCXX_END_NAMESPACE_VERSION
  2571. } // namespace std
  2572.  
  2573. #endif // C++11
  2574.  
  2575. #endif // _GLIBCXX_FUNCTIONAL

functional

这个实现的原理与上面分析的大致相同,使用函数指针实现多态,也使用了small object optimization。

注:标准库的文件的缩进是2格,有时8个空格会用一个tab代替,在将tab显示为4字节的编辑器中缩进会比较乱,我已经把tab全部替换为8个空格;很多人缩进习惯是4格,但如果把2格全部替换成4格也会乱了格式,所以以下摘录自标准库文件的代码全部都是2格缩进。

2.1 类型系统

类型之间的关系,无非是继承、嵌套、组合。这个实现中三者都有。

关于继承,你也许会问,我们刚才不是说了这种实现没法用继承吗?实际上没有矛盾。刚才说的继承,是接口上的继承,讲得更具体点就是要继承虚函数,是一种is-a的关系;而这里的继承,是实现上的继承,是一种is-implemented-in-terms-of的关系,在语言层面大多是private继承。

在泛型编程中,还有一个关于继承的问题,就是在继承体系的哪一层引入模板参数。

嵌套,即类中定义嵌套类型,使类之间的结构更加清晰,在泛型编程中还可以简化设计。

组合,在于一个类的对象中包含其他类的对象,本应属于对象关系的范畴,但是在这个实现中,一个类一般不会在同一个scope内出现多个对象,因此我这里就直接把对象组合的概念拿来用了。

2.1.1 异常类

首先出现的是 bad_function_call 类型,这是一个异常类,当调用空 std::function 对象时抛出:

 class bad_function_call : public std::exception
{
public:
virtual ~bad_function_call() noexcept;
const char* what() const noexcept;
};

由于不是模板类(难得能在STL中发现非模板类),实现被编译好放在了目标文件中。虽然GCC开源,但既然这个类不太重要,而且稍微想想就能知道它是怎么实现的了,所以这里就不深究了。

相关的还有一个用于抛出异常的函数:

 void __throw_bad_function_call() __attribute__((__noreturn__));

在 <bits/functexcept.h> 中。同样只有声明没有定义。

2.1.2 数据存储

有关数据存储的类共有3个:

 class _Undefined_class;

 union _Nocopy_types
{
void* _M_object;
const void* _M_const_object;
void (*_M_function_pointer)();
void (_Undefined_class::*_M_member_pointer)();
}; union _Any_data
{
void* _M_access() { return &_M_pod_data[]; }
const void* _M_access() const { return &_M_pod_data[]; } template<typename _Tp>
_Tp&
_M_access()
{ return *static_cast<_Tp*>(_M_access()); } template<typename _Tp>
const _Tp&
_M_access() const
{ return *static_cast<const _Tp*>(_M_access()); } _Nocopy_types _M_unused;
char _M_pod_data[sizeof(_Nocopy_types)];
};

_Undefined_class ,顾名思义,连定义都没有,只是用于声明 _Nocopy_types 中的成员指针数据域,因为同一个平台上成员指针的大小是相同的。

_Nocopy_types ,是4种类型的联合体类型,分别为指针、常量指针、函数指针与成员指针。“nocopy”指的是这几种类型指向的对象类型,而不是本身。

_Any_data ,是两种类型的联合体类型,一个是 _Nocopy_types ,另一个是 char 数组,两者大小相等。后者是POD的,POD的好处多啊,memcpy可以用,最重要的是复制不会抛异常。非模板 _M_access() 返回指针,模板 _M_access() 返回解引用的结果,两者都有 const 重载。

2.1.3 辅助类

 enum _Manager_operation
{
__get_type_info,
__get_functor_ptr,
__clone_functor,
__destroy_functor
};

_Manager_operation ,枚举类,是前面所说控制 std::function 的函数指针需要的参数类型。定义了4种操作:获得 type_info 、获得仿函数(就是函数对象)指针、复制仿函数、销毁(析构)仿函数。从这个定义中可以看出,1.4节所说的各种功能中,需要延迟调用的,除了函数对象调用以外,都可以通过这4个功能来组合起来。我们后面还会进一步探讨这个问题。

 template<typename _Tp>
struct __is_location_invariant
: integral_constant<bool, (is_pointer<_Tp>::value
|| is_member_pointer<_Tp>::value)>
{ };

__is_location_invariant ,一个trait类,判断一个类型是不是“位置不变”的。从字面上来理解,一个类型如果是“位置不变”的,那么对于一个这种类型的对象,无论它复制到哪里,各个对象的底层表示都是相同的。在这个定义中,一个类型是“位置不变”的,当且仅当它是一个指针或成员指针,与一般的理解有所不同(更新:后来改为 template<typename _Tp> struct __is_location_invariant : is_trivially_copyable<_Tp>::type { }; ,这就比较容易理解了)。

 template<typename _Tp>
struct _Simple_type_wrapper
{
_Simple_type_wrapper(_Tp __value) : __value(__value) { } _Tp __value;
}; template<typename _Tp>
struct __is_location_invariant<_Simple_type_wrapper<_Tp> >
: __is_location_invariant<_Tp>
{ };

_Simple_type_wrapper ,一个简单的包装器,用于避免 void* 与指针的指针之间类型转换的 const 问题。以及 __is_location_invariant 对 _Simple_type_wrapper 的偏特化。

2.1.4 内存管理基类

类 _Function_base 定义了一系列用于管理函数对象内存的函数,这是一个非模板类:

 class _Function_base
{
public:
static const std::size_t _M_max_size = sizeof(_Nocopy_types);
static const std::size_t _M_max_align = __alignof__(_Nocopy_types); template<typename _Functor>
class _Base_manager; template<typename _Functor>
class _Ref_manager; _Function_base() : _M_manager() { } ~_Function_base()
{
if (_M_manager)
_M_manager(_M_functor, _M_functor, __destroy_functor);
} bool _M_empty() const { return !_M_manager; } typedef bool (*_Manager_type)(_Any_data&, const _Any_data&,
_Manager_operation); _Any_data _M_functor;
_Manager_type _M_manager;
};

_Function_base 是 std::function 的实现基类,定义了两个静态常量,用于后面的trait类;两个内部类,用于包装静态方法;函数指针类型 _Manager_type 的对象 _M_manager ,用于存取 _Any_data 类型的 _M_functor 中的数据;构造函数,将函数指针置为空;析构函数,调用函数指针,销毁函数对象;_M_empty() 方法,检测内部是否存有函数对象。

我们来看其中的 _Base_manager 类:

 template<typename _Functor>
class _Base_manager
{
protected:
static const bool __stored_locally =
(__is_location_invariant<_Functor>::value
&& sizeof(_Functor) <= _M_max_size
&& __alignof__(_Functor) <= _M_max_align
&& (_M_max_align % __alignof__(_Functor) == )); typedef integral_constant<bool, __stored_locally> _Local_storage; static _Functor*
_M_get_pointer(const _Any_data& __source); static void
_M_clone(_Any_data& __dest, const _Any_data& __source, true_type); static void
_M_clone(_Any_data& __dest, const _Any_data& __source, false_type); static void
_M_destroy(_Any_data& __victim, true_type); static void
_M_destroy(_Any_data& __victim, false_type); public:
static bool
_M_manager(_Any_data& __dest, const _Any_data& __source,
_Manager_operation __op); static void
_M_init_functor(_Any_data& __functor, _Functor&& __f); template<typename _Signature>
static bool
_M_not_empty_function(const function<_Signature>& __f); template<typename _Tp>
static bool
_M_not_empty_function(const _Tp*& __fp); template<typename _Class, typename _Tp>
static bool
_M_not_empty_function(_Tp _Class::* const& __mp); template<typename _Tp>
static bool
_M_not_empty_function(const _Tp&); private:
static void
_M_init_functor(_Any_data& __functor, _Functor&& __f, true_type); static void
_M_init_functor(_Any_data& __functor, _Functor&& __f, false_type);
};

定义了一个静态布尔常量 __stored_locally ,它为真当且仅当 __is_location_invariant trait为真、仿函数放得下、仿函数的align符合两个要求。然后再反过来根据这个值定义trait类 _Local_storage (标准库里一般都是根据value trait来生成value)。

其余几个静态方法,顾名思义即可。有个值得思考的问题,就是为什么 _M_init_functor 是public的,没有被放进 _M_manager 呢?

再来看 _Ref_manager 类:

 template<typename _Functor>
class _Ref_manager : public _Base_manager<_Functor*>
{
typedef _Function_base::_Base_manager<_Functor*> _Base; public:
static bool
_M_manager(_Any_data& __dest, const _Any_data& __source,
_Manager_operation __op); static void
_M_init_functor(_Any_data& __functor, reference_wrapper<_Functor> __f);
};

_Ref_manager 继承自 _Base_manager 类,覆写了两个静态方法。

2.1.5 仿函数调用

起辅助作用的模板函数 __callable_functor :

 template<typename _Functor>
inline _Functor&
__callable_functor(_Functor& __f)
{ return __f; } template<typename _Member, typename _Class>
inline _Mem_fn<_Member _Class::*>
__callable_functor(_Member _Class::* &__p)
{ return std::mem_fn(__p); } template<typename _Member, typename _Class>
inline _Mem_fn<_Member _Class::*>
__callable_functor(_Member _Class::* const &__p)
{ return std::mem_fn(__p); } template<typename _Member, typename _Class>
inline _Mem_fn<_Member _Class::*>
__callable_functor(_Member _Class::* volatile &__p)
{ return std::mem_fn(__p); } template<typename _Member, typename _Class>
inline _Mem_fn<_Member _Class::*>
__callable_functor(_Member _Class::* const volatile &__p)
{ return std::mem_fn(__p); }

对非成员指针类型,直接返回参数本身;对成员指针类型,返回 mem_fn() 的结果(将类对象转换为第一个参数;这个标准库函数的实现不在这篇文章中涉及),并有cv-qualified重载。它改变了调用的形式,把所有的参数都放在了小括号中。

_Function_handler 类,管理仿函数调用:

 template<typename _Signature, typename _Functor>
class _Function_handler; template<typename _Res, typename _Functor, typename... _ArgTypes>
class _Function_handler<_Res(_ArgTypes...), _Functor>
: public _Function_base::_Base_manager<_Functor>
{
typedef _Function_base::_Base_manager<_Functor> _Base; public:
static _Res
_M_invoke(const _Any_data& __functor, _ArgTypes... __args);
}; template<typename _Functor, typename... _ArgTypes>
class _Function_handler<void(_ArgTypes...), _Functor>
: public _Function_base::_Base_manager<_Functor>
{
typedef _Function_base::_Base_manager<_Functor> _Base; public:
static void
_M_invoke(const _Any_data& __functor, _ArgTypes... __args);
}; template<typename _Res, typename _Functor, typename... _ArgTypes>
class _Function_handler<_Res(_ArgTypes...), reference_wrapper<_Functor> >
: public _Function_base::_Ref_manager<_Functor>
{
typedef _Function_base::_Ref_manager<_Functor> _Base; public:
static _Res
_M_invoke(const _Any_data& __functor, _ArgTypes... __args);
}; template<typename _Functor, typename... _ArgTypes>
class _Function_handler<void(_ArgTypes...), reference_wrapper<_Functor> >
: public _Function_base::_Ref_manager<_Functor>
{
typedef _Function_base::_Ref_manager<_Functor> _Base; public:
static void
_M_invoke(const _Any_data& __functor, _ArgTypes... __args);
}; template<typename _Class, typename _Member, typename _Res,
typename... _ArgTypes>
class _Function_handler<_Res(_ArgTypes...), _Member _Class::*>
: public _Function_handler<void(_ArgTypes...), _Member _Class::*>
{
typedef _Function_handler<void(_ArgTypes...), _Member _Class::*>
_Base; public:
static _Res
_M_invoke(const _Any_data& __functor, _ArgTypes... __args);
}; template<typename _Class, typename _Member, typename... _ArgTypes>
class _Function_handler<void(_ArgTypes...), _Member _Class::*>
: public _Function_base::_Base_manager<
_Simple_type_wrapper< _Member _Class::* > >
{
typedef _Member _Class::* _Functor;
typedef _Simple_type_wrapper<_Functor> _Wrapper;
typedef _Function_base::_Base_manager<_Wrapper> _Base; public:
static bool
_M_manager(_Any_data& __dest, const _Any_data& __source,
_Manager_operation __op); static void
_M_invoke(const _Any_data& __functor, _ArgTypes... __args);
};

共有6个特化版本:返回值类型为 void 、其他;函数对象类型为 std::reference_wrapper 、成员指针、其他。

继承自 _Function_base::_Base_manager 或 _Function_base::_Ref_manager ,提供了静态方法 _M_invoke() ,用于仿函数调用。有一个覆写的 _M_manager() ,表面上看是一个偏特化有覆写,实际上是两个,因为返回非 void 的成员指针偏特化版本还继承了其对应 void 偏特化版本。

2.1.6 接口定义

终于回到伟大的 std::function 了,但是我们还得再看点别的:

 template<typename _Arg, typename _Result>
struct unary_function
{
typedef _Arg argument_type; typedef _Result result_type;
}; template<typename _Arg1, typename _Arg2, typename _Result>
struct binary_function
{
typedef _Arg1 first_argument_type; typedef _Arg2 second_argument_type; typedef _Result result_type;
};

std::unary_function 与 std::binary_function ,定义了一元和二元函数的参数类型与返回值类型。

 template<typename _Res, typename... _ArgTypes>
struct _Maybe_unary_or_binary_function { }; template<typename _Res, typename _T1>
struct _Maybe_unary_or_binary_function<_Res, _T1>
: std::unary_function<_T1, _Res> { }; template<typename _Res, typename _T1, typename _T2>
struct _Maybe_unary_or_binary_function<_Res, _T1, _T2>
: std::binary_function<_T1, _T2, _Res> { };

_Maybe_unary_or_binary_function 类,当模板参数表示的函数为一元或二元时,分别继承 std::unary_function 与 std::binary_function 。

现在可以给出 std::function 类定义与方法声明:

 template<typename _Signature>
class function; template<typename _Res, typename... _ArgTypes>
class function<_Res(_ArgTypes...)>
: public _Maybe_unary_or_binary_function<_Res, _ArgTypes...>,
private _Function_base
{
typedef _Res _Signature_type(_ArgTypes...); template<typename _Functor>
using _Invoke = decltype(__callable_functor(std::declval<_Functor&>())
(std::declval<_ArgTypes>()...) ); template<typename _CallRes, typename _Res1>
struct _CheckResult
: is_convertible<_CallRes, _Res1> { }; template<typename _CallRes>
struct _CheckResult<_CallRes, void>
: true_type { }; template<typename _Functor>
using _Callable = _CheckResult<_Invoke<_Functor>, _Res>; template<typename _Cond, typename _Tp>
using _Requires = typename enable_if<_Cond::value, _Tp>::type; public:
typedef _Res result_type; function() noexcept; function(nullptr_t) noexcept; function(const function& __x); function(function&& __x); // TODO: needs allocator_arg_t template<typename _Functor,
typename = _Requires<_Callable<_Functor>, void>>
function(_Functor); function&
operator=(const function& __x); function&
operator=(function&& __x); function&
operator=(nullptr_t); template<typename _Functor>
_Requires<_Callable<_Functor>, function&>
operator=(_Functor&& __f); template<typename _Functor>
function&
operator=(reference_wrapper<_Functor> __f) noexcept;
void swap(function& __x); // TODO: needs allocator_arg_t
/*
template<typename _Functor, typename _Alloc>
void
assign(_Functor&& __f, const _Alloc& __a);
*/ explicit operator bool() const noexcept; _Res operator()(_ArgTypes... __args) const; #ifdef __GXX_RTTI
const type_info& target_type() const noexcept; template<typename _Functor> _Functor* target() noexcept; template<typename _Functor> const _Functor* target() const noexcept;
#endif private:
typedef _Res (*_Invoker_type)(const _Any_data&, _ArgTypes...);
_Invoker_type _M_invoker;
}; template<typename _Res, typename... _Args>
inline bool
operator==(const function<_Res(_Args...)>& __f, nullptr_t) noexcept; template<typename _Res, typename... _Args>
inline bool
operator==(nullptr_t, const function<_Res(_Args...)>& __f) noexcept; template<typename _Res, typename... _Args>
inline bool
operator!=(const function<_Res(_Args...)>& __f, nullptr_t) noexcept; template<typename _Res, typename... _Args>
inline bool
operator!=(nullptr_t, const function<_Res(_Args...)>& __f) noexcept; template<typename _Res, typename... _Args>
inline void
swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y);

前面说过,std::function 类的模板参数是一个函数类型。一个函数类型也是一个类型;std::function 只在模板参数是函数类型时才有意义;因此,有用的 std::function 是一个特化的模板,需要一个声明。标准库规定没有特化的声明是没有定义的。

std::function 继承自两个类:公有继承模板类 _Maybe_unary_or_binary_function ,私有继承非模板类 _Function_base 。

前者是公有继承,但实际上没有继承虚函数,不属于接口继承,而是实现继承,继承的是基类定义的类型别名。因为这些类型别名是面向客户的,所以必须公有继承。这个继承使 std::function 在不同数量的模板参数的实例化下定义不同的类型别名。继承是实现这种功能的唯一方法,SFINAE不行。(这是本文第一次出现SFINAE这个词,我默认你看得懂。这是泛型编程中的常用技巧,如果不会请参考这篇文章或Google。)

后者是私有继承,也属于实现继承,继承了基类的两个数据域与几个静态方法。

_Signature_type 是一个类型别名,就是模板参数,是一个函数类型。

_Invoke 是一个别名模板,就是仿函数被按参数类型调用的返回类型。如果不能调用,根据SFINAE,S错误不会E,但这个别名只有一个定义,在使用的地方所有S都E了,编译器还是会给E。

_CheckResult 是一个trait类,检测第一个模板参数能否转换为第二个。另有第二个参数为 void 的偏特化,在类型检测上使返回类型为 void 的 std::function 对象能支持任何返回值的函数对象。

_Callable 也是一个trait类,利用上面两个定义检测仿函数类型与 std::function 模板参数是否匹配。

_Requires 是一个有趣的别名模板,如果模板参数中第一个value trait为 true ,则定义为第二个模板参数,否则未定义(是没有,不是 void ),使用时将交给SFINAE处理。它大致上实现了C++20中 require 关键字的功能。实际上concept在2005年就有proposal了,一路从C++0x拖到C++20。我计划在C++20标准正式发布之前写一篇文章完整介绍concept。

result_type 是模板参数函数类型的返回值类型,与基类中定义的相同。

在类定义最后的私有段,还定义了一个函数指针类型以及该类型的一个对象,这是第二个函数指针。

其余的各种函数,在1.4节都介绍过了。

2.1.7 类型关系

讲了这么多类型,你记住它们之间的关系了吗?我们再来自顶向下地梳理一遍。

一个 std::function 对象中包含一个函数指针,它会被初始化为 _Function_handler 类中的静态函数的指针。std::function 与 _Function_handler 类之间,可以认为是组合关系。

std::function 继承自 _Maybe_unary_or_binary_function 与 _Function_base ,两者都是实现继承。

_Function_base 中有 _Base_manager 与 _Ref_manager 两个嵌套类型,其中后者还继承了前者,并覆写了几个方法。两个类定义了一系列静态方法,继承只是为了避免代码重复。

_Function_base 含有两个数据域,一个是函数指针,_Function_base 与两个嵌套类型之间既是嵌套又是组合;另一个是 _Any_data 类型对象,_Function_base 与 _Any_data 之间是组合关系。

而 _Any_data 是一个联合体,是两部分相同大小数据的联合,分别是 char 数组和 _Nocopy_types 类型对象,后者又是4种基本类型的联合。

其余的一些类与函数,都是起辅助作用的。至此,对 std::function 定义的分析就结束了。

2.2 方法的功能与实现

2.2.1 多态性的体现

之前一直讲,std::function 是一个多态的函数对象包装器,其中的难点就在于多态。什么是多态?你能看到这里,水平肯定不低,不知道多态是不可能的。Wikipedia对polymorphism的定义是:In programming languages and type theory, polymorphism is the provision of a single interface to entities of different types or the use of a single symbol to represent multiple different types.

可以说,我们要在 std::function 中处理好多态,就是要处理好类型。类型当然不能一个个枚举,但可以分类。这里可以分类的有两处:接口类型,即组成模板参数的类型,以及实现类型,即绑定的仿函数的类型。下面,我们就从这两个角度入手,分析 std::function 是如何实现的。

2.2.2 本地函数对象

先根据仿函数类型分类,可以在 std::function 对象内部存储的,无需heap空间的,在这一节讨论。相关的方法有以下3个:

 template<typename _Functor>
static void
_Function_base::_Base_manager<_Functor>::
_M_init_functor(_Any_data& __functor, _Functor&& __f, true_type)
{ new (__functor._M_access()) _Functor(std::move(__f)); } template<typename _Functor>
static void
_Function_base::_Base_manager<_Functor>::
_M_clone(_Any_data& __dest, const _Any_data& __source, true_type)
{
new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
} template<typename _Functor>
static void
_Function_base::_Base_manager<_Functor>::
_M_destroy(_Any_data& __victim, true_type)
{
__victim._M_access<_Functor>().~_Functor();
}

_M_init_functor 用于初始化对象,在空白区域上用placement new 移动构造了函数对象。

_M_clone 用于复制对象,在目标的空白区域上用placement new 拷贝构造和函数对象。

_M_destroy 用于销毁对象,对函数对象显式调用了析构函数。

2.2.3 heap函数对象

然后来看函数对象存储在heap上的情况:

 template<typename _Functor>
static void
_Function_base::_Base_manager<_Functor>::
_M_init_functor(_Any_data& __functor, _Functor&& __f, false_type)
{ __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); } template<typename _Functor>
static void
_Function_base::_Base_manager<_Functor>::
_M_clone(_Any_data& __dest, const _Any_data& __source, false_type)
{
__dest._M_access<_Functor*>() =
new _Functor(*__source._M_access<_Functor*>());
} template<typename _Functor>
static void
_Function_base::_Base_manager<_Functor>::
_M_destroy(_Any_data& __victim, false_type)
{
delete __victim._M_access<_Functor*>();
}

_M_access<_Functor*>() 将空白区域解释为仿函数的指针,并返回其引用,实现了这片区域的分时复用。前两个方法都比前一种情况多一层间接,而销毁方法则直接调用了 delete 。

2.2.4 两种存储结构如何统一

尽管我们不得不分类讨论,但为了方便使用,还需要一个统一的接口。不知你有没有注意到,上面每一个方法都有一个未命名的参数放在最后,在方法中也没有用到。前一种情况,这个参数都是 true_type 类型,而后一种都是 false_type 类型。这个技巧称为tag dispatching,在调用时根据类型特征确定这个位置的参数类型,从而通过重载决定调用哪一个。

 template<typename _Functor>
static void
_Function_base::_Base_manager<_Functor>::
_M_init_functor(_Any_data& __functor, _Functor&& __f)
{ _M_init_functor(__functor, std::move(__f), _Local_storage()); } template<typename _Functor>
static bool
_Function_base::_Base_manager<_Functor>::
_M_manager(_Any_data& __dest, const _Any_data& __source,
_Manager_operation __op)
{
switch (__op)
{
#ifdef __GXX_RTTI
case __get_type_info:
__dest._M_access<const type_info*>() = &typeid(_Functor);
break;
#endif
case __get_functor_ptr:
__dest._M_access<_Functor*>() = _M_get_pointer(__source);
break; case __clone_functor:
_M_clone(__dest, __source, _Local_storage());
break; case __destroy_functor:
_M_destroy(__dest, _Local_storage());
break;
}
return false;
}

这个版本的 _M_init_functor() 只有两个参数,加上第三个参数委托给重载版本处理,这第三个参数是一个 _Local_storage 类的对象,它根据 __stored_locally 而成为 true_type 与 false_type ,从而区分开两个重载。

_M_manager() 方法,同样地,利用tag dispatching把另两组方法统一起来。它通过第三个枚举类型参数来确定需要的操作。

但是,这个方法的返回值是 bool ,怎么传出 type_info 与函数对象指针呢?它们将返回值写入第一个参数所指向的空间中。说起利用参数来传递返回值,我就想起C中的指针、C++中的引用、RVO、Java中的包裹类型、C#中的 out 关键字……这里的处理方法不仅解决了返回值的问题,同时也使各个操作的参数统一起来。

一个值得思考的问题是为什么不把 _M_init_functor() 也放到 _M_manager() 中去?答案是,调用 _M_init_functor() 的地方在 std::function 的模板构造或模板赋值函数中,此时是知道仿函数类型的;而其他操作被调用时,主调函数是不知道仿函数类型的,就必须用函数指针存储起来;为了节省空间,就引入一个枚举类 _Manager_operation ,把几种操作合并到一个函数中。

实际上这一层可以先不统一,就是写两种情况的 _M_manager ,然后到上一层再统一,但是会增加代码量。

除此以外,还有一种简单的方法将两者统一:

 template<typename _Functor>
static _Functor*
_Function_base::_Base_manager<_Functor>::
_M_get_pointer(const _Any_data& __source)
{
const _Functor* __ptr =
__stored_locally? std::__addressof(__source._M_access<_Functor>())
: __source._M_access<_Functor*>();
return const_cast<_Functor*>(__ptr);
}

三目运算符的条件是一个静态常量,编译器会优化,不浪费程序空间,也不需要在运行时判断,效果与前一种方法相同。至于另外两个方法(指函数)为什么不用这种方法(指将两种情况统一的方法),可能是为了可读性吧。

2.2.5 根据形式区分仿函数类型

在下面一层解决了不同存储结构的问题后,我们还要考虑几种特殊情况。

_M_not_empty_function() 用于判断参数是否非空,而不同类型的判定方法是不同的。这里的解决方案很简单,模板方法重载即可。

 template<typename _Functor>
template<typename _Signature>
static bool
_Function_base::_Base_manager<_Functor>::
_M_not_empty_function(const function<_Signature>& __f)
{ return static_cast<bool>(__f); } template<typename _Functor>
template<typename _Tp>
static bool
_Function_base::_Base_manager<_Functor>::
_M_not_empty_function(const _Tp*& __fp)
{ return __fp; } template<typename _Functor>
template<typename _Class, typename _Tp>
static bool
_Function_base::_Base_manager<_Functor>::
_M_not_empty_function(_Tp _Class::* const& __mp)
{ return __mp; } template<typename _Functor>
template<typename _Tp>
static bool
_Function_base::_Base_manager<_Functor>::
_M_not_empty_function(const _Tp&)
{ return true; }

在调用时,普通函数对象、std::reference_wrapper 对象与成员指针的调用方法是不同的,也需要分类讨论。

 template<typename _Res, typename _Functor, typename... _ArgTypes>
static _Res
_Function_handler<_Res(_ArgTypes...), _Functor>::
_M_invoke(const _Any_data& __functor, _ArgTypes... __args)
{
return (*_Base::_M_get_pointer(__functor))(
std::forward<_ArgTypes>(__args)...);
}

对于普通函数对象,函数调用没什么特殊的。注意自定义 operator() 必须是 const 的。

对于 std::reference_wrapper 对象,由于包装的对象存储为指针,因此存储结构与普通函数对象有所不同,相应地调用也不同。

 template<typename _Functor>
static void
_Function_base::_Ref_manager<_Functor>::
_M_init_functor(_Any_data& __functor, reference_wrapper<_Functor> __f)
{
_Base::_M_init_functor(__functor, std::__addressof(__f.get()));
} template<typename _Functor>
static bool
_Function_base::_Ref_manager<_Functor>::
_M_manager(_Any_data& __dest, const _Any_data& __source,
_Manager_operation __op)
{
switch (__op)
{
#ifdef __GXX_RTTI
case __get_type_info:
__dest._M_access<const type_info*>() = &typeid(_Functor);
break;
#endif
case __get_functor_ptr:
__dest._M_access<_Functor*>() = *_Base::_M_get_pointer(__source);
return is_const<_Functor>::value;
break; default:
_Base::_M_manager(__dest, __source, __op);
}
return false;
} template<typename _Res, typename _Functor, typename... _ArgTypes>
static _Res
_Function_handler<_Res(_ArgTypes...), reference_wrapper<_Functor> >::
_M_invoke(const _Any_data& __functor, _ArgTypes... __args)
{
return __callable_functor(**_Base::_M_get_pointer(__functor))(
std::forward<_ArgTypes>(__args)...);
}

碰到两个星号是不是有点晕?其实只要想,一般情况下存储函数对象的地方现在存储指针,所以要获得原始对象,只需要比一般情况多一次解引用,这样就容易理解了。

对于成员指针,情况又有一点不一样:

 template<typename _Class, typename _Member, typename... _ArgTypes>
static bool
_Function_handler<void(_ArgTypes...), _Member _Class::*>::
_M_manager(_Any_data& __dest, const _Any_data& __source,
_Manager_operation __op)
{
switch (__op)
{
#ifdef __GXX_RTTI
case __get_type_info:
__dest._M_access<const type_info*>() = &typeid(_Functor);
break;
#endif
case __get_functor_ptr:
__dest._M_access<_Functor*>() =
&_Base::_M_get_pointer(__source)->__value;
break; default:
_Base::_M_manager(__dest, __source, __op);
}
return false;
} template<typename _Class, typename _Member, typename _Res,
typename... _ArgTypes>
static _Res
_Function_handler<_Res(_ArgTypes...), _Member _Class::*>::
_M_invoke(const _Any_data& __functor, _ArgTypes... __args)
{
return std::mem_fn(_Base::_M_get_pointer(__functor)->__value)(
std::forward<_ArgTypes>(__args)...);
}

我一直说“成员指针”,而不是“成员函数指针”,是因为数据成员指针也是可以绑定的,这种情况在 std::mem_fn() 中已经处理好了。

void 返回类型的偏特化本应接下来讨论,但之前讲过,这个函数被通过继承复用了。实际上,如果把这里的 void 改为模板类型,然后交换两个 _Function_handler 偏特化的继承关系,效果还是一样的,所以就在这里先讨论了。

最后一个需要区分的类型,是返回值类型,属于接口类型。之前都是非 void 版本,下面还有几个 void 的偏特化:

 template<typename _Functor, typename... _ArgTypes>
static void
_Function_handler<void(_ArgTypes...), _Functor>::
_M_invoke(const _Any_data& __functor, _ArgTypes... __args)
{
(*_Base::_M_get_pointer(__functor))(
std::forward<_ArgTypes>(__args)...);
} template<typename _Functor, typename... _ArgTypes>
static void
_Function_handler<void(_ArgTypes...), reference_wrapper<_Functor> >::
_M_invoke(const _Any_data& __functor, _ArgTypes... __args)
{
__callable_functor(**_Base::_M_get_pointer(__functor))(
std::forward<_ArgTypes>(__args)...);
} template<typename _Class, typename _Member, typename... _ArgTypes>
static void
_Function_handler<void(_ArgTypes...), _Member _Class::*>::
_M_invoke(const _Any_data& __functor, _ArgTypes... __args)
{
std::mem_fn(_Base::_M_get_pointer(__functor)->__value)(
std::forward<_ArgTypes>(__args)...);
}

void 只是删除了 return 关键字的非 void 版本,因此 void 返回类型的 std::function 对象可以绑定任何返回值的函数对象。

2.2.6 实现组装成接口

我们终于讨论完了各种情况,接下来让我们来见证 std::function 的大和谐:如何用这些方法组装成 std::function 。

 template<typename _Res, typename... _ArgTypes>
function<_Res(_ArgTypes...)>::
function() noexcept
: _Function_base() { } template<typename _Res, typename... _ArgTypes>
function<_Res(_ArgTypes...)>::
function(nullptr_t) noexcept
: _Function_base() { } template<typename _Res, typename... _ArgTypes>
function<_Res(_ArgTypes...)>::
function(function&& __x) : _Function_base()
{
__x.swap(*this);
} template<typename _Res, typename... _ArgTypes>
auto
function<_Res(_ArgTypes...)>::
operator=(const function& __x)
-> function&
{
function(__x).swap(*this);
return *this;
} template<typename _Res, typename... _ArgTypes>
auto
function<_Res(_ArgTypes...)>::
operator=(function&& __x)
-> function&
{
function(std::move(__x)).swap(*this);
return *this;
} template<typename _Res, typename... _ArgTypes>
auto
function<_Res(_ArgTypes...)>::
operator=(nullptr_t)
-> function&
{
if (_M_manager)
{
_M_manager(_M_functor, _M_functor, __destroy_functor);
_M_manager = ;
_M_invoker = ;
}
return *this;
} template<typename _Functor>
auto
function<_Res(_ArgTypes...)>::
operator=(_Functor&& __f)
-> _Requires<_Callable<_Functor>, function&>
{
function(std::forward<_Functor>(__f)).swap(*this);
return *this;
} template<typename _Res, typename... _ArgTypes>
template<typename _Functor>
auto
function<_Res(_ArgTypes...)>::
-> function&
operator=(reference_wrapper<_Functor> __f) noexcept
{
function(__f).swap(*this);
return *this;
} template<typename _Res, typename... _ArgTypes>
void
function<_Res(_ArgTypes...)>::
swap(function& __x)
{
std::swap(_M_functor, __x._M_functor);
std::swap(_M_manager, __x._M_manager);
std::swap(_M_invoker, __x._M_invoker);
} template<typename _Res, typename... _ArgTypes>
function<_Res(_ArgTypes...)>::
operator bool() const noexcept
{ return !_M_empty(); } template<typename _Res, typename... _ArgTypes>
function<_Res(_ArgTypes...)>::
function(const function& __x)
: _Function_base()
{
if (static_cast<bool>(__x))
{
_M_invoker = __x._M_invoker;
_M_manager = __x._M_manager;
__x._M_manager(_M_functor, __x._M_functor, __clone_functor);
}
} template<typename _Res, typename... _ArgTypes>
template<typename _Functor, typename>
function<_Res(_ArgTypes...)>::
function(_Functor __f)
: _Function_base()
{
typedef _Function_handler<_Signature_type, _Functor> _My_handler; if (_My_handler::_M_not_empty_function(__f))
{
_My_handler::_M_init_functor(_M_functor, std::move(__f));
_M_invoker = &_My_handler::_M_invoke;
_M_manager = &_My_handler::_M_manager;
}
} template<typename _Res, typename... _ArgTypes>
_Res
function<_Res(_ArgTypes...)>::
operator()(_ArgTypes... __args) const
{
if (_M_empty())
__throw_bad_function_call();
return _M_invoker(_M_functor, std::forward<_ArgTypes>(__args)...);
} template<typename _Res, typename... _ArgTypes>
const type_info&
function<_Res(_ArgTypes...)>::
target_type() const noexcept
{
if (_M_manager)
{
_Any_data __typeinfo_result;
_M_manager(__typeinfo_result, _M_functor, __get_type_info);
return *__typeinfo_result._M_access<const type_info*>();
}
else
return typeid(void);
} template<typename _Res, typename... _ArgTypes>
template<typename _Functor>
_Functor*
function<_Res(_ArgTypes...)>::
target() noexcept
{
if (typeid(_Functor) == target_type() && _M_manager)
{
_Any_data __ptr;
if (_M_manager(__ptr, _M_functor, __get_functor_ptr)
&& !is_const<_Functor>::value)
return ;
else
return __ptr._M_access<_Functor*>();
}
else
return ;
} template<typename _Res, typename... _ArgTypes>
template<typename _Functor>
const _Functor*
function<_Res(_ArgTypes...)>::
target() const noexcept
{
if (typeid(_Functor) == target_type() && _M_manager)
{
_Any_data __ptr;
_M_manager(__ptr, _M_functor, __get_functor_ptr);
return __ptr._M_access<const _Functor*>();
}
else
return ;
} template<typename _Res, typename... _Args>
inline bool
operator==(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
{ return !static_cast<bool>(__f); } template<typename _Res, typename... _Args>
inline bool
operator==(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
{ return !static_cast<bool>(__f); } template<typename _Res, typename... _Args>
inline bool
operator!=(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
{ return static_cast<bool>(__f); } template<typename _Res, typename... _Args>
inline bool
operator!=(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
{ return static_cast<bool>(__f); } template<typename _Res, typename... _Args>
inline void
swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y)
{ __x.swap(__y); }

我们从 swap() 开始入手。swap() 方法只是简单地将三个数据成员交换了一下,这是正确的,因为它们存储的都是POD类型。我认为,这个实现对函数对象存储在本地的条件的限制太过严格,大小合适的可trivial复制的函数对象也应该可以存储在本地。

在 swap() 的基础上,拷贝构造、移动构造、拷贝赋值、移动赋值函数很自然地构建起来了,而且只用到了 swap() 方法。这种技巧称为copy-and-swap。这也就解释了为什么 std::function 需要那么多延迟调用的操作而表示操作的枚举类只需要定义4种操作。

swap() 还可以成为异常安全的基础。由于以上方法只涉及到 swap() ,而 swap() 方法是不抛异常的,因此两个移动函数是 noexcept 的,两个拷贝函数也能保证在栈空间足够时不抛异常,在抛异常时不会出现内存泄漏。

其余的方法,有了前面的基础,看代码就能读懂了。

后记

写这篇文章花了好久呀。这是我第一次写这么长的博客,希望你能有所收获。如果有不懂的地方,可以在评论区留言。如果有任何错误,烦请指正。

我是从实现的角度来写的这篇文章,如果你对其中的一些技巧(SFINAE、tag dispatching)不太熟悉的话,理解起来可能有点困难。相关资料[8]介绍了 function 类的设计思路,从无到有的构建过程比较容易理解。相关资料[9]分析了另一个版本的 std::function 实现,可供参考。

文章内容已经很充实了,但是没有图片,不太直观。有空我会加上图片的,这样更容易理解。

另外,在我实现完自己的 function 类以后,还会对这篇文章作一点补充。自己造一遍轮子,总会有更深刻的感受吧。

附录

相关资料:

[1] Naive std::function implementation

[2] How is std::function implemented?

[3] std::function - cppreference.com

[4] The space of design choices for std::function

[5] How true is “Want Speed? Pass by value”

[6] C++奇淫巧技之SFINAE

[7] What is the copy-and-swap idiom?

[8] std::function 基本实现

[9] std::function 源码分析

剖析std::function接口与实现的更多相关文章

  1. C++11 std::function用法

    转自 http://www.hankcs.com/program/cpp/c11-std-function-usage.html function可以将普通函数,lambda表达式和函数对象类统一起来 ...

  2. Lambda表达式与Function接口

    Lambda表达式是一个匿名函数.C++ 11和 java 8 相继引入了有关对Lambda表达式的支持. Lambda表达式对于高级语言而言并不是必要的,对于Java而言它的功能和一个简易的接口差不 ...

  3. C++中的仿函数,std::function和bind()的用法

    1.仿函数:又叫std::function,是C++中的一个模板类 2.C语言中的函数指针: int  add(int a,int b) { return a+b; } typedef int (*f ...

  4. std::bind接口与实现

    前言 最近想起半年前鸽下来的Haskell,重温了一下忘得精光的语法,读了几个示例程序,挺带感的,于是函数式编程的草就种得更深了.又去Google了一下C++与FP,找到了一份近乎完美的讲义,然后被带 ...

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

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

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

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

  7. typedef 函数指针 数组 std::function

    1.整型指针 typedef int* PINT;或typedef int *PINT; 2.结构体 typedef struct { double data;}DATA,  *PDATA;  //D ...

  8. Function接口 – Java8中java.util.function包下的函数式接口

    Introduction to Functional Interfaces – A concept recreated in Java 8 Any java developer around the ...

  9. callable object与新增的function相关 C++11中万能的可调用类型声明std::function<...>

    在c++11中,一个callable object(可调用对象)可以是函数指针.lambda表达式.重载()的某类对象.bind包裹的某对象等等,有时需要统一管理一些这几类对象,新增的function ...

随机推荐

  1. 29 z-index

    这个东西非常简单,它有四大特性,每个特性你记住了,页面布局就不会出现找不到盒子的情况. z-index 值表示谁压着谁,数值大的压盖住数值小的, 只有定位了的元素,才能有z-index,也就是说,不管 ...

  2. WPF基于3D对象捕获鼠标点击事件

    ModelUIElment3DUIElment3D是.NET3.5新增的类,替代了ModelVisual3D.ModelVisual3D有2个派生类ModelUIElment3D和ContainerU ...

  3. 使用elasticsearch启动项目报错failed to load elasticsearch nodes 。。。。。No type specified for field [name]

    failed to load elasticsearch nodes .....No type specified for field [name]翻译: 加载ElasticSearch节点失败... ...

  4. JS中的闭包 详细解析大全(面试避必考题)

    JS中闭包的介绍   闭包的概念 闭包就是能够读取其他函数内部变量的函数. 一.变量的作用域 要理解闭包,首先必须理解Javascript特殊的变量作用域. 变量的作用域无非就是两种:全局变量和局部变 ...

  5. docker无法启动

    docker无法启动 docker启动时报错Error starting daemon: SELinux is not supported with the overlay2 graph driver ...

  6. C#使用 SSL Socket 建立 Client 与 Server 连接

    当 Client 与 Server 需要建立一个沟通的管道时可以使用 Socket 的方式建立一个信道,但是使用单纯的 Socket 联机信道可能会担心传输数据的过程中可能被截取修改因而不够安全,为了 ...

  7. Linux不重启识别新添加的磁盘

    现网的一台EXSI 下的虚拟机一般在进行配置变更后都会通过重启来识别新增的配置,不过业务侧某台主机因为业务需要无法重启,想通过不重启直接识别护容上去的新磁盘.经测试,发现如下方可以解决. 1.通过ex ...

  8. C++类的完美单元测试方案——基于C++11扩展的friend语法

    版权相关声明:本文所述方案来自于<深入理解C++11—C++11新特性解析与应用>(Michael Wong著,机械工业出版社,2016.4重印)一书的学习. 项目管理中,C语言工程做单元 ...

  9. 【Linux】一步一步学Linux——VMware虚拟机三种网络模式详解(07)

    目录 00. 目录 01. 虚拟网络连接组件 02. 常见网络连接配置 03. 桥接模式 04. NAT 模式 05. 仅主机模式 06. 自定义模式 07. 附录 00. 目录 @ 01. 虚拟网络 ...

  10. C++学习书籍推荐《C++标准库(第一版)》下载

    百度云及其他网盘下载地址:点我 编辑推荐 <C++标准程序库:自修教程与参考手册>编辑推荐:C++标准程序库提供了一组通用类别(classes)和界面(interfaes),可大幅扩充C+ ...