剖析std::function接口与实现
目录
前言
为什么要剖析 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 是一个模板类,模板参数是一个类型(注意是一个类型,不是好几个类型)。我们可以这么写:
std::function<int(double)> f;
f 是一个可调用对象,参数为 double,返回值为 int 。你也许会问,这里既规定了参数类型又规定了返回值类型,怎么就成了一个类型呢?确实是一个类型,int(double) 是一个函数类型(注意不是函数指针)。
std::function 要包装所有合适类型的对象,就必须有对应的构造函数,所以这是个模板构造函数。参数不是通用引用而是直接传值:
template <typename F>
function(F);
可能是为了让编译器对空对象进行优化。同样还有一个模板赋值函数,参数是通用引用。
每个构造函数都有一个添加了 std::allocator_arg_t 作为第一个参数、内存分配器对象作为第二个参数的版本,C++17中已经移除(GCC从未提供,可能是因为 std::function 的内存分配无法自定义)。同样删除的还有 assign ,也是与内存分配器相关的。
另外有一个以 std::reference_wrapper 作为参数的赋值函数:
template <typename F>
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行,默认折叠,慎入。
// <functional> -*- C++ -*- // Copyright (C) 2001-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version. // This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional
// permissions described in the GCC Runtime Library Exception, version
// 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and
// a copy of the GCC Runtime Library Exception along with this program;
// see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
// <http://www.gnu.org/licenses/>. /*
* Copyright (c) 1997
* Silicon Graphics Computer Systems, Inc.
*
* Permission to use, copy, modify, distribute and sell this software
* and its documentation for any purpose is hereby granted without fee,
* provided that the above copyright notice appear in all copies and
* that both that copyright notice and this permission notice appear
* in supporting documentation. Silicon Graphics makes no
* representations about the suitability of this software for any
* purpose. It is provided "as is" without express or implied warranty.
*
*/ /** @file include/functional
* This is a Standard C++ Library header.
*/ #ifndef _GLIBCXX_FUNCTIONAL
#define _GLIBCXX_FUNCTIONAL 1 #pragma GCC system_header #include <bits/c++config.h>
#include <bits/stl_function.h> #if __cplusplus >= 201103L #include <typeinfo>
#include <new>
#include <tuple>
#include <type_traits>
#include <bits/functexcept.h>
#include <bits/functional_hash.h> namespace std _GLIBCXX_VISIBILITY(default)
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION template<typename _MemberPointer>
class _Mem_fn;
template<typename _Tp, typename _Class>
_Mem_fn<_Tp _Class::*>
mem_fn(_Tp _Class::*) noexcept; _GLIBCXX_HAS_NESTED_TYPE(result_type) /// If we have found a result_type, extract it.
template<bool _Has_result_type, typename _Functor>
struct _Maybe_get_result_type
{ }; template<typename _Functor>
struct _Maybe_get_result_type<true, _Functor>
{ typedef typename _Functor::result_type result_type; }; /**
* Base class for any function object that has a weak result type, as
* defined in 3.3/3 of TR1.
*/
template<typename _Functor>
struct _Weak_result_type_impl
: _Maybe_get_result_type<__has_result_type<_Functor>::value, _Functor>
{ }; /// Retrieve the result type for a function type.
template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes...)>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes......)>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes...) const>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes......) const>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes...) volatile>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes......) volatile>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes...) const volatile>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(_ArgTypes......) const volatile>
{ typedef _Res result_type; }; /// Retrieve the result type for a function reference.
template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(&)(_ArgTypes...)>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(&)(_ArgTypes......)>
{ typedef _Res result_type; }; /// Retrieve the result type for a function pointer.
template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(*)(_ArgTypes...)>
{ typedef _Res result_type; }; template<typename _Res, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res(*)(_ArgTypes......)>
{ typedef _Res result_type; }; /// Retrieve result type for a member function pointer.
template<typename _Res, typename _Class, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes...)>
{ typedef _Res result_type; }; template<typename _Res, typename _Class, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes......)>
{ typedef _Res result_type; }; /// Retrieve result type for a const member function pointer.
template<typename _Res, typename _Class, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes...) const>
{ typedef _Res result_type; }; template<typename _Res, typename _Class, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes......) const>
{ typedef _Res result_type; }; /// Retrieve result type for a volatile member function pointer.
template<typename _Res, typename _Class, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes...) volatile>
{ typedef _Res result_type; }; template<typename _Res, typename _Class, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes......) volatile>
{ typedef _Res result_type; }; /// Retrieve result type for a const volatile member function pointer.
template<typename _Res, typename _Class, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes...)
const volatile>
{ typedef _Res result_type; }; template<typename _Res, typename _Class, typename... _ArgTypes>
struct _Weak_result_type_impl<_Res (_Class::*)(_ArgTypes......)
const volatile>
{ typedef _Res result_type; }; /**
* Strip top-level cv-qualifiers from the function object and let
* _Weak_result_type_impl perform the real work.
*/
template<typename _Functor>
struct _Weak_result_type
: _Weak_result_type_impl<typename remove_cv<_Functor>::type>
{ }; /// Determines if the type _Tp derives from unary_function.
template<typename _Tp>
struct _Derives_from_unary_function : __sfinae_types
{
private:
template<typename _T1, typename _Res>
static __one __test(const volatile unary_function<_T1, _Res>*); // It's tempting to change "..." to const volatile void*, but
// that fails when _Tp is a function type.
static __two __test(...); public:
static const bool value = sizeof(__test((_Tp*))) == ;
}; /// Determines if the type _Tp derives from binary_function.
template<typename _Tp>
struct _Derives_from_binary_function : __sfinae_types
{
private:
template<typename _T1, typename _T2, typename _Res>
static __one __test(const volatile binary_function<_T1, _T2, _Res>*); // It's tempting to change "..." to const volatile void*, but
// that fails when _Tp is a function type.
static __two __test(...); public:
static const bool value = sizeof(__test((_Tp*))) == ;
}; /**
* Invoke a function object, which may be either a member pointer or a
* function object. The first parameter will tell which.
*/
template<typename _Functor, typename... _Args>
inline
typename enable_if<
(!is_member_pointer<_Functor>::value
&& !is_function<_Functor>::value
&& !is_function<typename remove_pointer<_Functor>::type>::value),
typename result_of<_Functor&(_Args&&...)>::type
>::type
__invoke(_Functor& __f, _Args&&... __args)
{
return __f(std::forward<_Args>(__args)...);
} template<typename _Functor, typename... _Args>
inline
typename enable_if<
(is_member_pointer<_Functor>::value
&& !is_function<_Functor>::value
&& !is_function<typename remove_pointer<_Functor>::type>::value),
typename result_of<_Functor(_Args&&...)>::type
>::type
__invoke(_Functor& __f, _Args&&... __args)
{
return std::mem_fn(__f)(std::forward<_Args>(__args)...);
} // To pick up function references (that will become function pointers)
template<typename _Functor, typename... _Args>
inline
typename enable_if<
(is_pointer<_Functor>::value
&& is_function<typename remove_pointer<_Functor>::type>::value),
typename result_of<_Functor(_Args&&...)>::type
>::type
__invoke(_Functor __f, _Args&&... __args)
{
return __f(std::forward<_Args>(__args)...);
} /**
* Knowing which of unary_function and binary_function _Tp derives
* from, derives from the same and ensures that reference_wrapper
* will have a weak result type. See cases below.
*/
template<bool _Unary, bool _Binary, typename _Tp>
struct _Reference_wrapper_base_impl; // None of the nested argument types.
template<typename _Tp>
struct _Reference_wrapper_base_impl<false, false, _Tp>
: _Weak_result_type<_Tp>
{ }; // Nested argument_type only.
template<typename _Tp>
struct _Reference_wrapper_base_impl<true, false, _Tp>
: _Weak_result_type<_Tp>
{
typedef typename _Tp::argument_type argument_type;
}; // Nested first_argument_type and second_argument_type only.
template<typename _Tp>
struct _Reference_wrapper_base_impl<false, true, _Tp>
: _Weak_result_type<_Tp>
{
typedef typename _Tp::first_argument_type first_argument_type;
typedef typename _Tp::second_argument_type second_argument_type;
}; // All the nested argument types.
template<typename _Tp>
struct _Reference_wrapper_base_impl<true, true, _Tp>
: _Weak_result_type<_Tp>
{
typedef typename _Tp::argument_type argument_type;
typedef typename _Tp::first_argument_type first_argument_type;
typedef typename _Tp::second_argument_type second_argument_type;
}; _GLIBCXX_HAS_NESTED_TYPE(argument_type)
_GLIBCXX_HAS_NESTED_TYPE(first_argument_type)
_GLIBCXX_HAS_NESTED_TYPE(second_argument_type) /**
* Derives from unary_function or binary_function when it
* can. Specializations handle all of the easy cases. The primary
* template determines what to do with a class type, which may
* derive from both unary_function and binary_function.
*/
template<typename _Tp>
struct _Reference_wrapper_base
: _Reference_wrapper_base_impl<
__has_argument_type<_Tp>::value,
__has_first_argument_type<_Tp>::value
&& __has_second_argument_type<_Tp>::value,
_Tp>
{ }; // - a function type (unary)
template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res(_T1)>
: unary_function<_T1, _Res>
{ }; template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res(_T1) const>
: unary_function<_T1, _Res>
{ }; template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res(_T1) volatile>
: unary_function<_T1, _Res>
{ }; template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res(_T1) const volatile>
: unary_function<_T1, _Res>
{ }; // - a function type (binary)
template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res(_T1, _T2)>
: binary_function<_T1, _T2, _Res>
{ }; template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res(_T1, _T2) const>
: binary_function<_T1, _T2, _Res>
{ }; template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res(_T1, _T2) volatile>
: binary_function<_T1, _T2, _Res>
{ }; template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res(_T1, _T2) const volatile>
: binary_function<_T1, _T2, _Res>
{ }; // - a function pointer type (unary)
template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res(*)(_T1)>
: unary_function<_T1, _Res>
{ }; // - a function pointer type (binary)
template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res(*)(_T1, _T2)>
: binary_function<_T1, _T2, _Res>
{ }; // - a pointer to member function type (unary, no qualifiers)
template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res (_T1::*)()>
: unary_function<_T1*, _Res>
{ }; // - a pointer to member function type (binary, no qualifiers)
template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res (_T1::*)(_T2)>
: binary_function<_T1*, _T2, _Res>
{ }; // - a pointer to member function type (unary, const)
template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res (_T1::*)() const>
: unary_function<const _T1*, _Res>
{ }; // - a pointer to member function type (binary, const)
template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res (_T1::*)(_T2) const>
: binary_function<const _T1*, _T2, _Res>
{ }; // - a pointer to member function type (unary, volatile)
template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res (_T1::*)() volatile>
: unary_function<volatile _T1*, _Res>
{ }; // - a pointer to member function type (binary, volatile)
template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res (_T1::*)(_T2) volatile>
: binary_function<volatile _T1*, _T2, _Res>
{ }; // - a pointer to member function type (unary, const volatile)
template<typename _Res, typename _T1>
struct _Reference_wrapper_base<_Res (_T1::*)() const volatile>
: unary_function<const volatile _T1*, _Res>
{ }; // - a pointer to member function type (binary, const volatile)
template<typename _Res, typename _T1, typename _T2>
struct _Reference_wrapper_base<_Res (_T1::*)(_T2) const volatile>
: binary_function<const volatile _T1*, _T2, _Res>
{ }; /**
* @brief Primary class template for reference_wrapper.
* @ingroup functors
* @{
*/
template<typename _Tp>
class reference_wrapper
: public _Reference_wrapper_base<typename remove_cv<_Tp>::type>
{
_Tp* _M_data; public:
typedef _Tp type; reference_wrapper(_Tp& __indata) noexcept
: _M_data(std::__addressof(__indata))
{ } reference_wrapper(_Tp&&) = delete; reference_wrapper(const reference_wrapper<_Tp>& __inref) noexcept
: _M_data(__inref._M_data)
{ } reference_wrapper&
operator=(const reference_wrapper<_Tp>& __inref) noexcept
{
_M_data = __inref._M_data;
return *this;
} operator _Tp&() const noexcept
{ return this->get(); } _Tp&
get() const noexcept
{ return *_M_data; } template<typename... _Args>
typename result_of<_Tp&(_Args&&...)>::type
operator()(_Args&&... __args) const
{
return __invoke(get(), std::forward<_Args>(__args)...);
}
}; /// Denotes a reference should be taken to a variable.
template<typename _Tp>
inline reference_wrapper<_Tp>
ref(_Tp& __t) noexcept
{ return reference_wrapper<_Tp>(__t); } /// Denotes a const reference should be taken to a variable.
template<typename _Tp>
inline reference_wrapper<const _Tp>
cref(const _Tp& __t) noexcept
{ return reference_wrapper<const _Tp>(__t); } template<typename _Tp>
void ref(const _Tp&&) = delete; template<typename _Tp>
void cref(const _Tp&&) = delete; /// Partial specialization.
template<typename _Tp>
inline reference_wrapper<_Tp>
ref(reference_wrapper<_Tp> __t) noexcept
{ return ref(__t.get()); } /// Partial specialization.
template<typename _Tp>
inline reference_wrapper<const _Tp>
cref(reference_wrapper<_Tp> __t) noexcept
{ return cref(__t.get()); } // @} group functors template<typename... _Types>
struct _Pack : integral_constant<size_t, sizeof...(_Types)>
{ }; template<typename _From, typename _To, bool = _From::value == _To::value>
struct _AllConvertible : false_type
{ }; template<typename... _From, typename... _To>
struct _AllConvertible<_Pack<_From...>, _Pack<_To...>, true>
: __and_<is_convertible<_From, _To>...>
{ }; template<typename _Tp1, typename _Tp2>
using _NotSame = __not_<is_same<typename std::decay<_Tp1>::type,
typename std::decay<_Tp2>::type>>; /**
* Derives from @c unary_function or @c binary_function, or perhaps
* nothing, depending on the number of arguments provided. The
* primary template is the basis case, which derives nothing.
*/
template<typename _Res, typename... _ArgTypes>
struct _Maybe_unary_or_binary_function { }; /// Derives from @c unary_function, as appropriate.
template<typename _Res, typename _T1>
struct _Maybe_unary_or_binary_function<_Res, _T1>
: std::unary_function<_T1, _Res> { }; /// Derives from @c binary_function, as appropriate.
template<typename _Res, typename _T1, typename _T2>
struct _Maybe_unary_or_binary_function<_Res, _T1, _T2>
: std::binary_function<_T1, _T2, _Res> { }; /// Implementation of @c mem_fn for member function pointers.
template<typename _Res, typename _Class, typename... _ArgTypes>
class _Mem_fn<_Res (_Class::*)(_ArgTypes...)>
: public _Maybe_unary_or_binary_function<_Res, _Class*, _ArgTypes...>
{
typedef _Res (_Class::*_Functor)(_ArgTypes...); template<typename _Tp, typename... _Args>
_Res
_M_call(_Tp&& __object, const volatile _Class *,
_Args&&... __args) const
{
return (std::forward<_Tp>(__object).*__pmf)
(std::forward<_Args>(__args)...);
} template<typename _Tp, typename... _Args>
_Res
_M_call(_Tp&& __ptr, const volatile void *, _Args&&... __args) const
{ return ((*__ptr).*__pmf)(std::forward<_Args>(__args)...); } // Require each _Args to be convertible to corresponding _ArgTypes
template<typename... _Args>
using _RequireValidArgs
= _Require<_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; // Require each _Args to be convertible to corresponding _ArgTypes
// and require _Tp is not _Class, _Class& or _Class*
template<typename _Tp, typename... _Args>
using _RequireValidArgs2
= _Require<_NotSame<_Class, _Tp>, _NotSame<_Class*, _Tp>,
_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; // Require each _Args to be convertible to corresponding _ArgTypes
// and require _Tp is _Class or derived from _Class
template<typename _Tp, typename... _Args>
using _RequireValidArgs3
= _Require<is_base_of<_Class, _Tp>,
_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; public:
typedef _Res result_type; explicit _Mem_fn(_Functor __pmf) : __pmf(__pmf) { } // Handle objects
template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(_Class& __object, _Args&&... __args) const
{ return (__object.*__pmf)(std::forward<_Args>(__args)...); } template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(_Class&& __object, _Args&&... __args) const
{
return (std::move(__object).*__pmf)(std::forward<_Args>(__args)...);
} // Handle pointers
template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(_Class* __object, _Args&&... __args) const
{ return (__object->*__pmf)(std::forward<_Args>(__args)...); } // Handle smart pointers, references and pointers to derived
template<typename _Tp, typename... _Args,
typename _Req = _RequireValidArgs2<_Tp, _Args...>>
_Res
operator()(_Tp&& __object, _Args&&... __args) const
{
return _M_call(std::forward<_Tp>(__object), &__object,
std::forward<_Args>(__args)...);
} template<typename _Tp, typename... _Args,
typename _Req = _RequireValidArgs3<_Tp, _Args...>>
_Res
operator()(reference_wrapper<_Tp> __ref, _Args&&... __args) const
{ return operator()(__ref.get(), std::forward<_Args>(__args)...); } private:
_Functor __pmf;
}; /// Implementation of @c mem_fn for const member function pointers.
template<typename _Res, typename _Class, typename... _ArgTypes>
class _Mem_fn<_Res (_Class::*)(_ArgTypes...) const>
: public _Maybe_unary_or_binary_function<_Res, const _Class*,
_ArgTypes...>
{
typedef _Res (_Class::*_Functor)(_ArgTypes...) const; template<typename _Tp, typename... _Args>
_Res
_M_call(_Tp&& __object, const volatile _Class *,
_Args&&... __args) const
{
return (std::forward<_Tp>(__object).*__pmf)
(std::forward<_Args>(__args)...);
} template<typename _Tp, typename... _Args>
_Res
_M_call(_Tp&& __ptr, const volatile void *, _Args&&... __args) const
{ return ((*__ptr).*__pmf)(std::forward<_Args>(__args)...); } template<typename... _Args>
using _RequireValidArgs
= _Require<_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; template<typename _Tp, typename... _Args>
using _RequireValidArgs2
= _Require<_NotSame<_Class, _Tp>, _NotSame<const _Class*, _Tp>,
_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; template<typename _Tp, typename... _Args>
using _RequireValidArgs3
= _Require<is_base_of<_Class, _Tp>,
_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; public:
typedef _Res result_type; explicit _Mem_fn(_Functor __pmf) : __pmf(__pmf) { } // Handle objects
template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(const _Class& __object, _Args&&... __args) const
{ return (__object.*__pmf)(std::forward<_Args>(__args)...); } template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(const _Class&& __object, _Args&&... __args) const
{
return (std::move(__object).*__pmf)(std::forward<_Args>(__args)...);
} // Handle pointers
template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(const _Class* __object, _Args&&... __args) const
{ return (__object->*__pmf)(std::forward<_Args>(__args)...); } // Handle smart pointers, references and pointers to derived
template<typename _Tp, typename... _Args,
typename _Req = _RequireValidArgs2<_Tp, _Args...>>
_Res operator()(_Tp&& __object, _Args&&... __args) const
{
return _M_call(std::forward<_Tp>(__object), &__object,
std::forward<_Args>(__args)...);
} template<typename _Tp, typename... _Args,
typename _Req = _RequireValidArgs3<_Tp, _Args...>>
_Res
operator()(reference_wrapper<_Tp> __ref, _Args&&... __args) const
{ return operator()(__ref.get(), std::forward<_Args>(__args)...); } private:
_Functor __pmf;
}; /// Implementation of @c mem_fn for volatile member function pointers.
template<typename _Res, typename _Class, typename... _ArgTypes>
class _Mem_fn<_Res (_Class::*)(_ArgTypes...) volatile>
: public _Maybe_unary_or_binary_function<_Res, volatile _Class*,
_ArgTypes...>
{
typedef _Res (_Class::*_Functor)(_ArgTypes...) volatile; template<typename _Tp, typename... _Args>
_Res
_M_call(_Tp&& __object, const volatile _Class *,
_Args&&... __args) const
{
return (std::forward<_Tp>(__object).*__pmf)
(std::forward<_Args>(__args)...);
} template<typename _Tp, typename... _Args>
_Res
_M_call(_Tp&& __ptr, const volatile void *, _Args&&... __args) const
{ return ((*__ptr).*__pmf)(std::forward<_Args>(__args)...); } template<typename... _Args>
using _RequireValidArgs
= _Require<_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; template<typename _Tp, typename... _Args>
using _RequireValidArgs2
= _Require<_NotSame<_Class, _Tp>, _NotSame<volatile _Class*, _Tp>,
_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; template<typename _Tp, typename... _Args>
using _RequireValidArgs3
= _Require<is_base_of<_Class, _Tp>,
_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; public:
typedef _Res result_type; explicit _Mem_fn(_Functor __pmf) : __pmf(__pmf) { } // Handle objects
template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(volatile _Class& __object, _Args&&... __args) const
{ return (__object.*__pmf)(std::forward<_Args>(__args)...); } template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(volatile _Class&& __object, _Args&&... __args) const
{
return (std::move(__object).*__pmf)(std::forward<_Args>(__args)...);
} // Handle pointers
template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(volatile _Class* __object, _Args&&... __args) const
{ return (__object->*__pmf)(std::forward<_Args>(__args)...); } // Handle smart pointers, references and pointers to derived
template<typename _Tp, typename... _Args,
typename _Req = _RequireValidArgs2<_Tp, _Args...>>
_Res
operator()(_Tp&& __object, _Args&&... __args) const
{
return _M_call(std::forward<_Tp>(__object), &__object,
std::forward<_Args>(__args)...);
} template<typename _Tp, typename... _Args,
typename _Req = _RequireValidArgs3<_Tp, _Args...>>
_Res
operator()(reference_wrapper<_Tp> __ref, _Args&&... __args) const
{ return operator()(__ref.get(), std::forward<_Args>(__args)...); } private:
_Functor __pmf;
}; /// Implementation of @c mem_fn for const volatile member function pointers.
template<typename _Res, typename _Class, typename... _ArgTypes>
class _Mem_fn<_Res (_Class::*)(_ArgTypes...) const volatile>
: public _Maybe_unary_or_binary_function<_Res, const volatile _Class*,
_ArgTypes...>
{
typedef _Res (_Class::*_Functor)(_ArgTypes...) const volatile; template<typename _Tp, typename... _Args>
_Res
_M_call(_Tp&& __object, const volatile _Class *,
_Args&&... __args) const
{
return (std::forward<_Tp>(__object).*__pmf)
(std::forward<_Args>(__args)...);
} template<typename _Tp, typename... _Args>
_Res
_M_call(_Tp&& __ptr, const volatile void *, _Args&&... __args) const
{ return ((*__ptr).*__pmf)(std::forward<_Args>(__args)...); } template<typename... _Args>
using _RequireValidArgs
= _Require<_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; template<typename _Tp, typename... _Args>
using _RequireValidArgs2
= _Require<_NotSame<_Class, _Tp>,
_NotSame<const volatile _Class*, _Tp>,
_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; template<typename _Tp, typename... _Args>
using _RequireValidArgs3
= _Require<is_base_of<_Class, _Tp>,
_AllConvertible<_Pack<_Args...>, _Pack<_ArgTypes...>>>; public:
typedef _Res result_type; explicit _Mem_fn(_Functor __pmf) : __pmf(__pmf) { } // Handle objects
template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(const volatile _Class& __object, _Args&&... __args) const
{ return (__object.*__pmf)(std::forward<_Args>(__args)...); } template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(const volatile _Class&& __object, _Args&&... __args) const
{
return (std::move(__object).*__pmf)(std::forward<_Args>(__args)...);
} // Handle pointers
template<typename... _Args, typename _Req = _RequireValidArgs<_Args...>>
_Res
operator()(const volatile _Class* __object, _Args&&... __args) const
{ return (__object->*__pmf)(std::forward<_Args>(__args)...); } // Handle smart pointers, references and pointers to derived
template<typename _Tp, typename... _Args,
typename _Req = _RequireValidArgs2<_Tp, _Args...>>
_Res operator()(_Tp&& __object, _Args&&... __args) const
{
return _M_call(std::forward<_Tp>(__object), &__object,
std::forward<_Args>(__args)...);
} template<typename _Tp, typename... _Args,
typename _Req = _RequireValidArgs3<_Tp, _Args...>>
_Res
operator()(reference_wrapper<_Tp> __ref, _Args&&... __args) const
{ return operator()(__ref.get(), std::forward<_Args>(__args)...); } private:
_Functor __pmf;
}; template<typename _Tp, bool>
struct _Mem_fn_const_or_non
{
typedef const _Tp& type;
}; template<typename _Tp>
struct _Mem_fn_const_or_non<_Tp, false>
{
typedef _Tp& type;
}; template<typename _Res, typename _Class>
class _Mem_fn<_Res _Class::*>
{
using __pm_type = _Res _Class::*; // This bit of genius is due to Peter Dimov, improved slightly by
// Douglas Gregor.
// Made less elegant to support perfect forwarding and noexcept.
template<typename _Tp>
auto
_M_call(_Tp&& __object, const _Class *) const noexcept
-> decltype(std::forward<_Tp>(__object).*std::declval<__pm_type&>())
{ return std::forward<_Tp>(__object).*__pm; } template<typename _Tp, typename _Up>
auto
_M_call(_Tp&& __object, _Up * const *) const noexcept
-> decltype((*std::forward<_Tp>(__object)).*std::declval<__pm_type&>())
{ return (*std::forward<_Tp>(__object)).*__pm; } template<typename _Tp>
auto
_M_call(_Tp&& __ptr, const volatile void*) const
noexcept(noexcept((*__ptr).*std::declval<__pm_type&>()))
-> decltype((*__ptr).*std::declval<__pm_type&>())
{ return (*__ptr).*__pm; } public:
explicit
_Mem_fn(_Res _Class::*__pm) noexcept : __pm(__pm) { } // Handle objects
_Res&
operator()(_Class& __object) const noexcept
{ return __object.*__pm; } const _Res&
operator()(const _Class& __object) const noexcept
{ return __object.*__pm; } _Res&&
operator()(_Class&& __object) const noexcept
{ return std::forward<_Class>(__object).*__pm; } const _Res&&
operator()(const _Class&& __object) const noexcept
{ return std::forward<const _Class>(__object).*__pm; } // Handle pointers
_Res&
operator()(_Class* __object) const noexcept
{ return __object->*__pm; } const _Res&
operator()(const _Class* __object) const noexcept
{ return __object->*__pm; } // Handle smart pointers and derived
template<typename _Tp, typename _Req = _Require<_NotSame<_Class*, _Tp>>>
auto
operator()(_Tp&& __unknown) const
noexcept(noexcept(std::declval<_Mem_fn*>()->_M_call
(std::forward<_Tp>(__unknown), &__unknown)))
-> decltype(this->_M_call(std::forward<_Tp>(__unknown), &__unknown))
{ return _M_call(std::forward<_Tp>(__unknown), &__unknown); } template<typename _Tp, typename _Req = _Require<is_base_of<_Class, _Tp>>>
auto
operator()(reference_wrapper<_Tp> __ref) const
noexcept(noexcept(std::declval<_Mem_fn&>()(__ref.get())))
-> decltype((*this)(__ref.get()))
{ return (*this)(__ref.get()); } private:
_Res _Class::*__pm;
}; // _GLIBCXX_RESOLVE_LIB_DEFECTS
// 2048. Unnecessary mem_fn overloads
/**
* @brief Returns a function object that forwards to the member
* pointer @a pm.
* @ingroup functors
*/
template<typename _Tp, typename _Class>
inline _Mem_fn<_Tp _Class::*>
mem_fn(_Tp _Class::* __pm) noexcept
{
return _Mem_fn<_Tp _Class::*>(__pm);
} /**
* @brief Determines if the given type _Tp is a function object
* should be treated as a subexpression when evaluating calls to
* function objects returned by bind(). [TR1 3.6.1]
* @ingroup binders
*/
template<typename _Tp>
struct is_bind_expression
: public false_type { }; /**
* @brief Determines if the given type _Tp is a placeholder in a
* bind() expression and, if so, which placeholder it is. [TR1 3.6.2]
* @ingroup binders
*/
template<typename _Tp>
struct is_placeholder
: public integral_constant<int, >
{ }; /** @brief The type of placeholder objects defined by libstdc++.
* @ingroup binders
*/
template<int _Num> struct _Placeholder { }; _GLIBCXX_END_NAMESPACE_VERSION /** @namespace std::placeholders
* @brief ISO C++11 entities sub-namespace for functional.
* @ingroup binders
*/
namespace placeholders
{
_GLIBCXX_BEGIN_NAMESPACE_VERSION
/* Define a large number of placeholders. There is no way to
* simplify this with variadic templates, because we're introducing
* unique names for each.
*/
extern const _Placeholder<> _1;
extern const _Placeholder<> _2;
extern const _Placeholder<> _3;
extern const _Placeholder<> _4;
extern const _Placeholder<> _5;
extern const _Placeholder<> _6;
extern const _Placeholder<> _7;
extern const _Placeholder<> _8;
extern const _Placeholder<> _9;
extern const _Placeholder<> _10;
extern const _Placeholder<> _11;
extern const _Placeholder<> _12;
extern const _Placeholder<> _13;
extern const _Placeholder<> _14;
extern const _Placeholder<> _15;
extern const _Placeholder<> _16;
extern const _Placeholder<> _17;
extern const _Placeholder<> _18;
extern const _Placeholder<> _19;
extern const _Placeholder<> _20;
extern const _Placeholder<> _21;
extern const _Placeholder<> _22;
extern const _Placeholder<> _23;
extern const _Placeholder<> _24;
extern const _Placeholder<> _25;
extern const _Placeholder<> _26;
extern const _Placeholder<> _27;
extern const _Placeholder<> _28;
extern const _Placeholder<> _29;
_GLIBCXX_END_NAMESPACE_VERSION
} _GLIBCXX_BEGIN_NAMESPACE_VERSION /**
* Partial specialization of is_placeholder that provides the placeholder
* number for the placeholder objects defined by libstdc++.
* @ingroup binders
*/
template<int _Num>
struct is_placeholder<_Placeholder<_Num> >
: public integral_constant<int, _Num>
{ }; template<int _Num>
struct is_placeholder<const _Placeholder<_Num> >
: public integral_constant<int, _Num>
{ }; /**
* Used by _Safe_tuple_element to indicate that there is no tuple
* element at this position.
*/
struct _No_tuple_element; /**
* Implementation helper for _Safe_tuple_element. This primary
* template handles the case where it is safe to use @c
* tuple_element.
*/
template<std::size_t __i, typename _Tuple, bool _IsSafe>
struct _Safe_tuple_element_impl
: tuple_element<__i, _Tuple> { }; /**
* Implementation helper for _Safe_tuple_element. This partial
* specialization handles the case where it is not safe to use @c
* tuple_element. We just return @c _No_tuple_element.
*/
template<std::size_t __i, typename _Tuple>
struct _Safe_tuple_element_impl<__i, _Tuple, false>
{
typedef _No_tuple_element type;
}; /**
* Like tuple_element, but returns @c _No_tuple_element when
* tuple_element would return an error.
*/
template<std::size_t __i, typename _Tuple>
struct _Safe_tuple_element
: _Safe_tuple_element_impl<__i, _Tuple,
(__i < tuple_size<_Tuple>::value)>
{ }; /**
* Maps an argument to bind() into an actual argument to the bound
* function object [TR1 3.6.3/5]. Only the first parameter should
* be specified: the rest are used to determine among the various
* implementations. Note that, although this class is a function
* object, it isn't entirely normal because it takes only two
* parameters regardless of the number of parameters passed to the
* bind expression. The first parameter is the bound argument and
* the second parameter is a tuple containing references to the
* rest of the arguments.
*/
template<typename _Arg,
bool _IsBindExp = is_bind_expression<_Arg>::value,
bool _IsPlaceholder = (is_placeholder<_Arg>::value > )>
class _Mu; /**
* If the argument is reference_wrapper<_Tp>, returns the
* underlying reference. [TR1 3.6.3/5 bullet 1]
*/
template<typename _Tp>
class _Mu<reference_wrapper<_Tp>, false, false>
{
public:
typedef _Tp& result_type; /* Note: This won't actually work for const volatile
* reference_wrappers, because reference_wrapper::get() is const
* but not volatile-qualified. This might be a defect in the TR.
*/
template<typename _CVRef, typename _Tuple>
result_type
operator()(_CVRef& __arg, _Tuple&) const volatile
{ return __arg.get(); }
}; /**
* If the argument is a bind expression, we invoke the underlying
* function object with the same cv-qualifiers as we are given and
* pass along all of our arguments (unwrapped). [TR1 3.6.3/5 bullet 2]
*/
template<typename _Arg>
class _Mu<_Arg, true, false>
{
public:
template<typename _CVArg, typename... _Args>
auto
operator()(_CVArg& __arg,
tuple<_Args...>& __tuple) const volatile
-> decltype(__arg(declval<_Args>()...))
{
// Construct an index tuple and forward to __call
typedef typename _Build_index_tuple<sizeof...(_Args)>::__type
_Indexes;
return this->__call(__arg, __tuple, _Indexes());
} private:
// Invokes the underlying function object __arg by unpacking all
// of the arguments in the tuple.
template<typename _CVArg, typename... _Args, std::size_t... _Indexes>
auto
__call(_CVArg& __arg, tuple<_Args...>& __tuple,
const _Index_tuple<_Indexes...>&) const volatile
-> decltype(__arg(declval<_Args>()...))
{
return __arg(std::forward<_Args>(get<_Indexes>(__tuple))...);
}
}; /**
* If the argument is a placeholder for the Nth argument, returns
* a reference to the Nth argument to the bind function object.
* [TR1 3.6.3/5 bullet 3]
*/
template<typename _Arg>
class _Mu<_Arg, false, true>
{
public:
template<typename _Signature> class result; template<typename _CVMu, typename _CVArg, typename _Tuple>
class result<_CVMu(_CVArg, _Tuple)>
{
// Add a reference, if it hasn't already been done for us.
// This allows us to be a little bit sloppy in constructing
// the tuple that we pass to result_of<...>.
typedef typename _Safe_tuple_element<(is_placeholder<_Arg>::value
- ), _Tuple>::type
__base_type; public:
typedef typename add_rvalue_reference<__base_type>::type type;
}; template<typename _Tuple>
typename result<_Mu(_Arg, _Tuple)>::type
operator()(const volatile _Arg&, _Tuple& __tuple) const volatile
{
return std::forward<typename result<_Mu(_Arg, _Tuple)>::type>(
::std::get<(is_placeholder<_Arg>::value - )>(__tuple));
}
}; /**
* If the argument is just a value, returns a reference to that
* value. The cv-qualifiers on the reference are the same as the
* cv-qualifiers on the _Mu object. [TR1 3.6.3/5 bullet 4]
*/
template<typename _Arg>
class _Mu<_Arg, false, false>
{
public:
template<typename _Signature> struct result; template<typename _CVMu, typename _CVArg, typename _Tuple>
struct result<_CVMu(_CVArg, _Tuple)>
{
typedef typename add_lvalue_reference<_CVArg>::type type;
}; // Pick up the cv-qualifiers of the argument
template<typename _CVArg, typename _Tuple>
_CVArg&&
operator()(_CVArg&& __arg, _Tuple&) const volatile
{ return std::forward<_CVArg>(__arg); }
}; /**
* Maps member pointers into instances of _Mem_fn but leaves all
* other function objects untouched. Used by tr1::bind(). The
* primary template handles the non--member-pointer case.
*/
template<typename _Tp>
struct _Maybe_wrap_member_pointer
{
typedef _Tp type; static const _Tp&
__do_wrap(const _Tp& __x)
{ return __x; } static _Tp&&
__do_wrap(_Tp&& __x)
{ return static_cast<_Tp&&>(__x); }
}; /**
* Maps member pointers into instances of _Mem_fn but leaves all
* other function objects untouched. Used by tr1::bind(). This
* partial specialization handles the member pointer case.
*/
template<typename _Tp, typename _Class>
struct _Maybe_wrap_member_pointer<_Tp _Class::*>
{
typedef _Mem_fn<_Tp _Class::*> type; static type
__do_wrap(_Tp _Class::* __pm)
{ return type(__pm); }
}; // Specialization needed to prevent "forming reference to void" errors when
// bind<void>() is called, because argument deduction instantiates
// _Maybe_wrap_member_pointer<void> outside the immediate context where
// SFINAE applies.
template<>
struct _Maybe_wrap_member_pointer<void>
{
typedef void type;
}; // std::get<I> for volatile-qualified tuples
template<std::size_t _Ind, typename... _Tp>
inline auto
__volget(volatile tuple<_Tp...>& __tuple)
-> typename tuple_element<_Ind, tuple<_Tp...>>::type volatile&
{ return std::get<_Ind>(const_cast<tuple<_Tp...>&>(__tuple)); } // std::get<I> for const-volatile-qualified tuples
template<std::size_t _Ind, typename... _Tp>
inline auto
__volget(const volatile tuple<_Tp...>& __tuple)
-> typename tuple_element<_Ind, tuple<_Tp...>>::type const volatile&
{ return std::get<_Ind>(const_cast<const tuple<_Tp...>&>(__tuple)); } /// Type of the function object returned from bind().
template<typename _Signature>
struct _Bind; template<typename _Functor, typename... _Bound_args>
class _Bind<_Functor(_Bound_args...)>
: public _Weak_result_type<_Functor>
{
typedef _Bind __self_type;
typedef typename _Build_index_tuple<sizeof...(_Bound_args)>::__type
_Bound_indexes; _Functor _M_f;
tuple<_Bound_args...> _M_bound_args; // Call unqualified
template<typename _Result, typename... _Args, std::size_t... _Indexes>
_Result
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>)
{
return _M_f(_Mu<_Bound_args>()
(get<_Indexes>(_M_bound_args), __args)...);
} // Call as const
template<typename _Result, typename... _Args, std::size_t... _Indexes>
_Result
__call_c(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>) const
{
return _M_f(_Mu<_Bound_args>()
(get<_Indexes>(_M_bound_args), __args)...);
} // Call as volatile
template<typename _Result, typename... _Args, std::size_t... _Indexes>
_Result
__call_v(tuple<_Args...>&& __args,
_Index_tuple<_Indexes...>) volatile
{
return _M_f(_Mu<_Bound_args>()
(__volget<_Indexes>(_M_bound_args), __args)...);
} // Call as const volatile
template<typename _Result, typename... _Args, std::size_t... _Indexes>
_Result
__call_c_v(tuple<_Args...>&& __args,
_Index_tuple<_Indexes...>) const volatile
{
return _M_f(_Mu<_Bound_args>()
(__volget<_Indexes>(_M_bound_args), __args)...);
} public:
template<typename... _Args>
explicit _Bind(const _Functor& __f, _Args&&... __args)
: _M_f(__f), _M_bound_args(std::forward<_Args>(__args)...)
{ } template<typename... _Args>
explicit _Bind(_Functor&& __f, _Args&&... __args)
: _M_f(std::move(__f)), _M_bound_args(std::forward<_Args>(__args)...)
{ } _Bind(const _Bind&) = default; _Bind(_Bind&& __b)
: _M_f(std::move(__b._M_f)), _M_bound_args(std::move(__b._M_bound_args))
{ } // Call unqualified
template<typename... _Args, typename _Result
= decltype( std::declval<_Functor>()(
_Mu<_Bound_args>()( std::declval<_Bound_args&>(),
std::declval<tuple<_Args...>&>() )... ) )>
_Result
operator()(_Args&&... __args)
{
return this->__call<_Result>(
std::forward_as_tuple(std::forward<_Args>(__args)...),
_Bound_indexes());
} // Call as const
template<typename... _Args, typename _Result
= decltype( std::declval<typename enable_if<(sizeof...(_Args) >= ),
typename add_const<_Functor>::type>::type>()(
_Mu<_Bound_args>()( std::declval<const _Bound_args&>(),
std::declval<tuple<_Args...>&>() )... ) )>
_Result
operator()(_Args&&... __args) const
{
return this->__call_c<_Result>(
std::forward_as_tuple(std::forward<_Args>(__args)...),
_Bound_indexes());
} // Call as volatile
template<typename... _Args, typename _Result
= decltype( std::declval<typename enable_if<(sizeof...(_Args) >= ),
typename add_volatile<_Functor>::type>::type>()(
_Mu<_Bound_args>()( std::declval<volatile _Bound_args&>(),
std::declval<tuple<_Args...>&>() )... ) )>
_Result
operator()(_Args&&... __args) volatile
{
return this->__call_v<_Result>(
std::forward_as_tuple(std::forward<_Args>(__args)...),
_Bound_indexes());
} // Call as const volatile
template<typename... _Args, typename _Result
= decltype( std::declval<typename enable_if<(sizeof...(_Args) >= ),
typename add_cv<_Functor>::type>::type>()(
_Mu<_Bound_args>()( std::declval<const volatile _Bound_args&>(),
std::declval<tuple<_Args...>&>() )... ) )>
_Result
operator()(_Args&&... __args) const volatile
{
return this->__call_c_v<_Result>(
std::forward_as_tuple(std::forward<_Args>(__args)...),
_Bound_indexes());
}
}; /// Type of the function object returned from bind<R>().
template<typename _Result, typename _Signature>
struct _Bind_result; template<typename _Result, typename _Functor, typename... _Bound_args>
class _Bind_result<_Result, _Functor(_Bound_args...)>
{
typedef _Bind_result __self_type;
typedef typename _Build_index_tuple<sizeof...(_Bound_args)>::__type
_Bound_indexes; _Functor _M_f;
tuple<_Bound_args...> _M_bound_args; // sfinae types
template<typename _Res>
struct __enable_if_void : enable_if<is_void<_Res>::value, int> { };
template<typename _Res>
struct __disable_if_void : enable_if<!is_void<_Res>::value, int> { }; // Call unqualified
template<typename _Res, typename... _Args, std::size_t... _Indexes>
_Result
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
typename __disable_if_void<_Res>::type = )
{
return _M_f(_Mu<_Bound_args>()
(get<_Indexes>(_M_bound_args), __args)...);
} // Call unqualified, return void
template<typename _Res, typename... _Args, std::size_t... _Indexes>
void
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
typename __enable_if_void<_Res>::type = )
{
_M_f(_Mu<_Bound_args>()
(get<_Indexes>(_M_bound_args), __args)...);
} // Call as const
template<typename _Res, typename... _Args, std::size_t... _Indexes>
_Result
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
typename __disable_if_void<_Res>::type = ) const
{
return _M_f(_Mu<_Bound_args>()
(get<_Indexes>(_M_bound_args), __args)...);
} // Call as const, return void
template<typename _Res, typename... _Args, std::size_t... _Indexes>
void
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
typename __enable_if_void<_Res>::type = ) const
{
_M_f(_Mu<_Bound_args>()
(get<_Indexes>(_M_bound_args), __args)...);
} // Call as volatile
template<typename _Res, typename... _Args, std::size_t... _Indexes>
_Result
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
typename __disable_if_void<_Res>::type = ) volatile
{
return _M_f(_Mu<_Bound_args>()
(__volget<_Indexes>(_M_bound_args), __args)...);
} // Call as volatile, return void
template<typename _Res, typename... _Args, std::size_t... _Indexes>
void
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
typename __enable_if_void<_Res>::type = ) volatile
{
_M_f(_Mu<_Bound_args>()
(__volget<_Indexes>(_M_bound_args), __args)...);
} // Call as const volatile
template<typename _Res, typename... _Args, std::size_t... _Indexes>
_Result
__call(tuple<_Args...>&& __args, _Index_tuple<_Indexes...>,
typename __disable_if_void<_Res>::type = ) const volatile
{
return _M_f(_Mu<_Bound_args>()
(__volget<_Indexes>(_M_bound_args), __args)...);
} // Call as const volatile, return void
template<typename _Res, typename... _Args, std::size_t... _Indexes>
void
__call(tuple<_Args...>&& __args,
_Index_tuple<_Indexes...>,
typename __enable_if_void<_Res>::type = ) const volatile
{
_M_f(_Mu<_Bound_args>()
(__volget<_Indexes>(_M_bound_args), __args)...);
} public:
typedef _Result result_type; template<typename... _Args>
explicit _Bind_result(const _Functor& __f, _Args&&... __args)
: _M_f(__f), _M_bound_args(std::forward<_Args>(__args)...)
{ } template<typename... _Args>
explicit _Bind_result(_Functor&& __f, _Args&&... __args)
: _M_f(std::move(__f)), _M_bound_args(std::forward<_Args>(__args)...)
{ } _Bind_result(const _Bind_result&) = default; _Bind_result(_Bind_result&& __b)
: _M_f(std::move(__b._M_f)), _M_bound_args(std::move(__b._M_bound_args))
{ } // Call unqualified
template<typename... _Args>
result_type
operator()(_Args&&... __args)
{
return this->__call<_Result>(
std::forward_as_tuple(std::forward<_Args>(__args)...),
_Bound_indexes());
} // Call as const
template<typename... _Args>
result_type
operator()(_Args&&... __args) const
{
return this->__call<_Result>(
std::forward_as_tuple(std::forward<_Args>(__args)...),
_Bound_indexes());
} // Call as volatile
template<typename... _Args>
result_type
operator()(_Args&&... __args) volatile
{
return this->__call<_Result>(
std::forward_as_tuple(std::forward<_Args>(__args)...),
_Bound_indexes());
} // Call as const volatile
template<typename... _Args>
result_type
operator()(_Args&&... __args) const volatile
{
return this->__call<_Result>(
std::forward_as_tuple(std::forward<_Args>(__args)...),
_Bound_indexes());
}
}; /**
* @brief Class template _Bind is always a bind expression.
* @ingroup binders
*/
template<typename _Signature>
struct is_bind_expression<_Bind<_Signature> >
: public true_type { }; /**
* @brief Class template _Bind is always a bind expression.
* @ingroup binders
*/
template<typename _Signature>
struct is_bind_expression<const _Bind<_Signature> >
: public true_type { }; /**
* @brief Class template _Bind is always a bind expression.
* @ingroup binders
*/
template<typename _Signature>
struct is_bind_expression<volatile _Bind<_Signature> >
: public true_type { }; /**
* @brief Class template _Bind is always a bind expression.
* @ingroup binders
*/
template<typename _Signature>
struct is_bind_expression<const volatile _Bind<_Signature>>
: public true_type { }; /**
* @brief Class template _Bind_result is always a bind expression.
* @ingroup binders
*/
template<typename _Result, typename _Signature>
struct is_bind_expression<_Bind_result<_Result, _Signature>>
: public true_type { }; /**
* @brief Class template _Bind_result is always a bind expression.
* @ingroup binders
*/
template<typename _Result, typename _Signature>
struct is_bind_expression<const _Bind_result<_Result, _Signature>>
: public true_type { }; /**
* @brief Class template _Bind_result is always a bind expression.
* @ingroup binders
*/
template<typename _Result, typename _Signature>
struct is_bind_expression<volatile _Bind_result<_Result, _Signature>>
: public true_type { }; /**
* @brief Class template _Bind_result is always a bind expression.
* @ingroup binders
*/
template<typename _Result, typename _Signature>
struct is_bind_expression<const volatile _Bind_result<_Result, _Signature>>
: public true_type { }; // Trait type used to remove std::bind() from overload set via SFINAE
// when first argument has integer type, so that std::bind() will
// not be a better match than ::bind() from the BSD Sockets API.
template<typename _Tp, typename _Tp2 = typename decay<_Tp>::type>
using __is_socketlike = __or_<is_integral<_Tp2>, is_enum<_Tp2>>; template<bool _SocketLike, typename _Func, typename... _BoundArgs>
struct _Bind_helper
{
typedef _Maybe_wrap_member_pointer<typename decay<_Func>::type>
__maybe_type;
typedef typename __maybe_type::type __func_type;
typedef _Bind<__func_type(typename decay<_BoundArgs>::type...)> type;
}; // Partial specialization for is_socketlike == true, does not define
// nested type so std::bind() will not participate in overload resolution
// when the first argument might be a socket file descriptor.
template<typename _Func, typename... _BoundArgs>
struct _Bind_helper<true, _Func, _BoundArgs...>
{ }; /**
* @brief Function template for std::bind.
* @ingroup binders
*/
template<typename _Func, typename... _BoundArgs>
inline typename
_Bind_helper<__is_socketlike<_Func>::value, _Func, _BoundArgs...>::type
bind(_Func&& __f, _BoundArgs&&... __args)
{
typedef _Bind_helper<false, _Func, _BoundArgs...> __helper_type;
typedef typename __helper_type::__maybe_type __maybe_type;
typedef typename __helper_type::type __result_type;
return __result_type(__maybe_type::__do_wrap(std::forward<_Func>(__f)),
std::forward<_BoundArgs>(__args)...);
} template<typename _Result, typename _Func, typename... _BoundArgs>
struct _Bindres_helper
{
typedef _Maybe_wrap_member_pointer<typename decay<_Func>::type>
__maybe_type;
typedef typename __maybe_type::type __functor_type;
typedef _Bind_result<_Result,
__functor_type(typename decay<_BoundArgs>::type...)>
type;
}; /**
* @brief Function template for std::bind<R>.
* @ingroup binders
*/
template<typename _Result, typename _Func, typename... _BoundArgs>
inline
typename _Bindres_helper<_Result, _Func, _BoundArgs...>::type
bind(_Func&& __f, _BoundArgs&&... __args)
{
typedef _Bindres_helper<_Result, _Func, _BoundArgs...> __helper_type;
typedef typename __helper_type::__maybe_type __maybe_type;
typedef typename __helper_type::type __result_type;
return __result_type(__maybe_type::__do_wrap(std::forward<_Func>(__f)),
std::forward<_BoundArgs>(__args)...);
} template<typename _Signature>
struct _Bind_simple; template<typename _Callable, typename... _Args>
struct _Bind_simple<_Callable(_Args...)>
{
typedef typename result_of<_Callable(_Args...)>::type result_type; template<typename... _Args2, typename = typename
enable_if< sizeof...(_Args) == sizeof...(_Args2)>::type>
explicit
_Bind_simple(const _Callable& __callable, _Args2&&... __args)
: _M_bound(__callable, std::forward<_Args2>(__args)...)
{ } template<typename... _Args2, typename = typename
enable_if< sizeof...(_Args) == sizeof...(_Args2)>::type>
explicit
_Bind_simple(_Callable&& __callable, _Args2&&... __args)
: _M_bound(std::move(__callable), std::forward<_Args2>(__args)...)
{ } _Bind_simple(const _Bind_simple&) = default;
_Bind_simple(_Bind_simple&&) = default; result_type
operator()()
{
typedef typename _Build_index_tuple<sizeof...(_Args)>::__type _Indices;
return _M_invoke(_Indices());
} private: template<std::size_t... _Indices>
typename result_of<_Callable(_Args...)>::type
_M_invoke(_Index_tuple<_Indices...>)
{
// std::bind always forwards bound arguments as lvalues,
// but this type can call functions which only accept rvalues.
return std::forward<_Callable>(std::get<>(_M_bound))(
std::forward<_Args>(std::get<_Indices+>(_M_bound))...);
} std::tuple<_Callable, _Args...> _M_bound;
}; template<typename _Func, typename... _BoundArgs>
struct _Bind_simple_helper
{
typedef _Maybe_wrap_member_pointer<typename decay<_Func>::type>
__maybe_type;
typedef typename __maybe_type::type __func_type;
typedef _Bind_simple<__func_type(typename decay<_BoundArgs>::type...)>
__type;
}; // Simplified version of std::bind for internal use, without support for
// unbound arguments, placeholders or nested bind expressions.
template<typename _Callable, typename... _Args>
typename _Bind_simple_helper<_Callable, _Args...>::__type
__bind_simple(_Callable&& __callable, _Args&&... __args)
{
typedef _Bind_simple_helper<_Callable, _Args...> __helper_type;
typedef typename __helper_type::__maybe_type __maybe_type;
typedef typename __helper_type::__type __result_type;
return __result_type(
__maybe_type::__do_wrap( std::forward<_Callable>(__callable)),
std::forward<_Args>(__args)...);
} /**
* @brief Exception class thrown when class template function's
* operator() is called with an empty target.
* @ingroup exceptions
*/
class bad_function_call : public std::exception
{
public:
virtual ~bad_function_call() noexcept; const char* what() const noexcept;
}; /**
* Trait identifying "location-invariant" types, meaning that the
* address of the object (or any of its members) will not escape.
* Also implies a trivial copy constructor and assignment operator.
*/
template<typename _Tp>
struct __is_location_invariant
: integral_constant<bool, (is_pointer<_Tp>::value
|| is_member_pointer<_Tp>::value)>
{ }; 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)];
}; enum _Manager_operation
{
__get_type_info,
__get_functor_ptr,
__clone_functor,
__destroy_functor
}; // Simple type wrapper that helps avoid annoying const problems
// when casting between void pointers and pointers-to-pointers.
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>
{ }; // Converts a reference to a function object into a callable
// function object.
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); } template<typename _Signature>
class function; /// Base class of all polymorphic function object wrappers.
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
{
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; // Retrieve a pointer to the function object
static _Functor*
_M_get_pointer(const _Any_data& __source)
{
const _Functor* __ptr =
__stored_locally? std::__addressof(__source._M_access<_Functor>())
/* have stored a pointer */ : __source._M_access<_Functor*>();
return const_cast<_Functor*>(__ptr);
} // Clone a location-invariant function object that fits within
// an _Any_data structure.
static void
_M_clone(_Any_data& __dest, const _Any_data& __source, true_type)
{
new (__dest._M_access()) _Functor(__source._M_access<_Functor>());
} // Clone a function object that is not location-invariant or
// that cannot fit into an _Any_data structure.
static void
_M_clone(_Any_data& __dest, const _Any_data& __source, false_type)
{
__dest._M_access<_Functor*>() =
new _Functor(*__source._M_access<_Functor*>());
} // Destroying a location-invariant object may still require
// destruction.
static void
_M_destroy(_Any_data& __victim, true_type)
{
__victim._M_access<_Functor>().~_Functor();
} // Destroying an object located on the heap.
static void
_M_destroy(_Any_data& __victim, false_type)
{
delete __victim._M_access<_Functor*>();
} public:
static bool
_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;
} static void
_M_init_functor(_Any_data& __functor, _Functor&& __f)
{ _M_init_functor(__functor, std::move(__f), _Local_storage()); } template<typename _Signature>
static bool
_M_not_empty_function(const function<_Signature>& __f)
{ return static_cast<bool>(__f); } template<typename _Tp>
static bool
_M_not_empty_function(const _Tp*& __fp)
{ return __fp; } template<typename _Class, typename _Tp>
static bool
_M_not_empty_function(_Tp _Class::* const& __mp)
{ return __mp; } template<typename _Tp>
static bool
_M_not_empty_function(const _Tp&)
{ return true; } private:
static void
_M_init_functor(_Any_data& __functor, _Functor&& __f, true_type)
{ new (__functor._M_access()) _Functor(std::move(__f)); } static void
_M_init_functor(_Any_data& __functor, _Functor&& __f, false_type)
{ __functor._M_access<_Functor*>() = new _Functor(std::move(__f)); }
}; 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)
{
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;
} static void
_M_init_functor(_Any_data& __functor, reference_wrapper<_Functor> __f)
{
_Base::_M_init_functor(__functor, std::__addressof(__f.get()));
}
}; _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;
}; 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)
{
return (*_Base::_M_get_pointer(__functor))(
std::forward<_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)
{
(*_Base::_M_get_pointer(__functor))(
std::forward<_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)
{
return __callable_functor(**_Base::_M_get_pointer(__functor))(
std::forward<_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)
{
__callable_functor(**_Base::_M_get_pointer(__functor))(
std::forward<_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)
{
return std::mem_fn(_Base::_M_get_pointer(__functor)->__value)(
std::forward<_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)
{
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;
} static void
_M_invoke(const _Any_data& __functor, _ArgTypes... __args)
{
std::mem_fn(_Base::_M_get_pointer(__functor)->__value)(
std::forward<_ArgTypes>(__args)...);
}
}; /**
* @brief Primary class template for std::function.
* @ingroup functors
*
* Polymorphic function wrapper.
*/
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; // [3.7.2.1] construct/copy/destroy /**
* @brief Default construct creates an empty function call wrapper.
* @post @c !(bool)*this
*/
function() noexcept
: _Function_base() { } /**
* @brief Creates an empty function call wrapper.
* @post @c !(bool)*this
*/
function(nullptr_t) noexcept
: _Function_base() { } /**
* @brief %Function copy constructor.
* @param __x A %function object with identical call signature.
* @post @c bool(*this) == bool(__x)
*
* The newly-created %function contains a copy of the target of @a
* __x (if it has one).
*/
function(const function& __x); /**
* @brief %Function move constructor.
* @param __x A %function object rvalue with identical call signature.
*
* The newly-created %function contains the target of @a __x
* (if it has one).
*/
function(function&& __x) : _Function_base()
{
__x.swap(*this);
} // TODO: needs allocator_arg_t /**
* @brief Builds a %function that targets a copy of the incoming
* function object.
* @param __f A %function object that is callable with parameters of
* type @c T1, @c T2, ..., @c TN and returns a value convertible
* to @c Res.
*
* The newly-created %function object will target a copy of
* @a __f. If @a __f is @c reference_wrapper<F>, then this function
* object will contain a reference to the function object @c
* __f.get(). If @a __f is a NULL function pointer or NULL
* pointer-to-member, the newly-created object will be empty.
*
* If @a __f is a non-NULL function pointer or an object of type @c
* reference_wrapper<F>, this function will not throw.
*/
template<typename _Functor,
typename = _Requires<_Callable<_Functor>, void>>
function(_Functor); /**
* @brief %Function assignment operator.
* @param __x A %function with identical call signature.
* @post @c (bool)*this == (bool)x
* @returns @c *this
*
* The target of @a __x is copied to @c *this. If @a __x has no
* target, then @c *this will be empty.
*
* If @a __x targets a function pointer or a reference to a function
* object, then this operation will not throw an %exception.
*/
function&
operator=(const function& __x)
{
function(__x).swap(*this);
return *this;
} /**
* @brief %Function move-assignment operator.
* @param __x A %function rvalue with identical call signature.
* @returns @c *this
*
* The target of @a __x is moved to @c *this. If @a __x has no
* target, then @c *this will be empty.
*
* If @a __x targets a function pointer or a reference to a function
* object, then this operation will not throw an %exception.
*/
function&
operator=(function&& __x)
{
function(std::move(__x)).swap(*this);
return *this;
} /**
* @brief %Function assignment to zero.
* @post @c !(bool)*this
* @returns @c *this
*
* The target of @c *this is deallocated, leaving it empty.
*/
function&
operator=(nullptr_t)
{
if (_M_manager)
{
_M_manager(_M_functor, _M_functor, __destroy_functor);
_M_manager = ;
_M_invoker = ;
}
return *this;
} /**
* @brief %Function assignment to a new target.
* @param __f A %function object that is callable with parameters of
* type @c T1, @c T2, ..., @c TN and returns a value convertible
* to @c Res.
* @return @c *this
*
* This %function object wrapper will target a copy of @a
* __f. If @a __f is @c reference_wrapper<F>, then this function
* object will contain a reference to the function object @c
* __f.get(). If @a __f is a NULL function pointer or NULL
* pointer-to-member, @c this object will be empty.
*
* If @a __f is a non-NULL function pointer or an object of type @c
* reference_wrapper<F>, this function will not throw.
*/
template<typename _Functor>
_Requires<_Callable<_Functor>, function&>
operator=(_Functor&& __f)
{
function(std::forward<_Functor>(__f)).swap(*this);
return *this;
} /// @overload
template<typename _Functor>
function&
operator=(reference_wrapper<_Functor> __f) noexcept
{
function(__f).swap(*this);
return *this;
} // [3.7.2.2] function modifiers /**
* @brief Swap the targets of two %function objects.
* @param __x A %function with identical call signature.
*
* Swap the targets of @c this function object and @a __f. This
* function will not throw an %exception.
*/
void swap(function& __x)
{
std::swap(_M_functor, __x._M_functor);
std::swap(_M_manager, __x._M_manager);
std::swap(_M_invoker, __x._M_invoker);
} // TODO: needs allocator_arg_t
/*
template<typename _Functor, typename _Alloc>
void
assign(_Functor&& __f, const _Alloc& __a)
{
function(allocator_arg, __a,
std::forward<_Functor>(__f)).swap(*this);
}
*/ // [3.7.2.3] function capacity /**
* @brief Determine if the %function wrapper has a target.
*
* @return @c true when this %function object contains a target,
* or @c false when it is empty.
*
* This function will not throw an %exception.
*/
explicit operator bool() const noexcept
{ return !_M_empty(); } // [3.7.2.4] function invocation /**
* @brief Invokes the function targeted by @c *this.
* @returns the result of the target.
* @throws bad_function_call when @c !(bool)*this
*
* The function call operator invokes the target function object
* stored by @c this.
*/
_Res operator()(_ArgTypes... __args) const; #ifdef __GXX_RTTI
// [3.7.2.5] function target access
/**
* @brief Determine the type of the target of this function object
* wrapper.
*
* @returns the type identifier of the target function object, or
* @c typeid(void) if @c !(bool)*this.
*
* This function will not throw an %exception.
*/
const type_info& target_type() const noexcept; /**
* @brief Access the stored target function object.
*
* @return Returns a pointer to the stored target function object,
* if @c typeid(Functor).equals(target_type()); otherwise, a NULL
* pointer.
*
* This function will not throw an %exception.
*/
template<typename _Functor> _Functor* target() noexcept; /// @overload
template<typename _Functor> const _Functor* target() const noexcept;
#endif private:
typedef _Res (*_Invoker_type)(const _Any_data&, _ArgTypes...);
_Invoker_type _M_invoker;
}; // Out-of-line member definitions.
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)...);
} #ifdef __GXX_RTTI
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 ;
}
#endif // [20.7.15.2.6] null pointer comparisons /**
* @brief Compares a polymorphic function object wrapper against 0
* (the NULL pointer).
* @returns @c true if the wrapper has no target, @c false otherwise
*
* This function will not throw an %exception.
*/
template<typename _Res, typename... _Args>
inline bool
operator==(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
{ return !static_cast<bool>(__f); } /// @overload
template<typename _Res, typename... _Args>
inline bool
operator==(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
{ return !static_cast<bool>(__f); } /**
* @brief Compares a polymorphic function object wrapper against 0
* (the NULL pointer).
* @returns @c false if the wrapper has no target, @c true otherwise
*
* This function will not throw an %exception.
*/
template<typename _Res, typename... _Args>
inline bool
operator!=(const function<_Res(_Args...)>& __f, nullptr_t) noexcept
{ return static_cast<bool>(__f); } /// @overload
template<typename _Res, typename... _Args>
inline bool
operator!=(nullptr_t, const function<_Res(_Args...)>& __f) noexcept
{ return static_cast<bool>(__f); } // [20.7.15.2.7] specialized algorithms /**
* @brief Swap the targets of two polymorphic function object wrappers.
*
* This function will not throw an %exception.
*/
template<typename _Res, typename... _Args>
inline void
swap(function<_Res(_Args...)>& __x, function<_Res(_Args...)>& __y)
{ __x.swap(__y); } _GLIBCXX_END_NAMESPACE_VERSION
} // namespace std #endif // C++11 #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?
剖析std::function接口与实现的更多相关文章
- C++11 std::function用法
转自 http://www.hankcs.com/program/cpp/c11-std-function-usage.html function可以将普通函数,lambda表达式和函数对象类统一起来 ...
- Lambda表达式与Function接口
Lambda表达式是一个匿名函数.C++ 11和 java 8 相继引入了有关对Lambda表达式的支持. Lambda表达式对于高级语言而言并不是必要的,对于Java而言它的功能和一个简易的接口差不 ...
- C++中的仿函数,std::function和bind()的用法
1.仿函数:又叫std::function,是C++中的一个模板类 2.C语言中的函数指针: int add(int a,int b) { return a+b; } typedef int (*f ...
- std::bind接口与实现
前言 最近想起半年前鸽下来的Haskell,重温了一下忘得精光的语法,读了几个示例程序,挺带感的,于是函数式编程的草就种得更深了.又去Google了一下C++与FP,找到了一份近乎完美的讲义,然后被带 ...
- C++11中的std::function
看看这段代码 先来看看下面这两行代码: std::function<void(EventKeyboard::KeyCode, Event*)> onKeyPressed; std::fun ...
- C++11之std::function和std::bind
std::function是可调用对象的包装器,它最重要的功能是实现延时调用: #include "stdafx.h" #include<iostream>// std ...
- typedef 函数指针 数组 std::function
1.整型指针 typedef int* PINT;或typedef int *PINT; 2.结构体 typedef struct { double data;}DATA, *PDATA; //D ...
- Function接口 – Java8中java.util.function包下的函数式接口
Introduction to Functional Interfaces – A concept recreated in Java 8 Any java developer around the ...
- callable object与新增的function相关 C++11中万能的可调用类型声明std::function<...>
在c++11中,一个callable object(可调用对象)可以是函数指针.lambda表达式.重载()的某类对象.bind包裹的某对象等等,有时需要统一管理一些这几类对象,新增的function ...
随机推荐
- 高中生也能读懂的Docker入门教程
Docker 是 Golang 编写的, 自 2013 年推出以来,受到越来越多的开发者的关注.如果你关注最新的技术发展,那么你一定听说过 Docker.不管是云服务还是微服务(Microservic ...
- RSA der加密 p12解密以及配合AES使用详解
在前面的文章中我有说过AES和RSA这两种加密方式,正好在前段时间再项目中有使用到,在这里再把这两种加密方式综合在一起写一下,具体到他们的使用,以及RSA各种加密文件的生成. 一: RSA各种加密相关 ...
- Spring Cloud Gateway使用
简介 Spring Cloud Gateway是Spring Cloud官方推出的网关框架,网关作为流量入口,在微服务系统中有着十分重要的作用,常用功能包括:鉴权.路由转发.熔断.限流等. Sprin ...
- Storm 学习之路(五)—— Storm编程模型详解
一.简介 下图为Strom的运行流程图,在开发Storm流处理程序时,我们需要采用内置或自定义实现spout(数据源)和bolt(处理单元),并通过TopologyBuilder将它们之间进行关联,形 ...
- tar命令压缩和解压
https://www.cnblogs.com/jyaray/archive/2011/04/30/2033362.html tar命令详解 -c: 建立压缩档案 -x:解压 -t:查看内容 -r:向 ...
- 浅谈Invoke 和 BegionInvoke的用法
很多人对Invoke和BeginInvoke理解不深刻,不知道该怎么应用,在这篇博文里将详细阐述Invoke和BeginInvoke的用法: 首先说下Invoke和BeginInvoke有两种用法: ...
- 趣解 ceph rgw multisite data sync 机制
multisite是ceph rgw对象数据异地容灾备份的一个有效方案,笔者希望深入理解该技术,并应用于生产环境中,然而rgw的这部分代码晦涩难懂,笔者多次尝试阅读,仍云里雾里不解其意,最终流着泪咬着 ...
- BZOJ 1001:[BeiJing2006]狼抓兔子(最小割)
http://www.lydsy.com/JudgeOnline/problem.php?id=1001 题意:中文. 思路:很明显是最小割,转化为最大流做.一开始看那么多点,但还是试了一下,居然过了 ...
- 使用java的MultipartFile实现layui官网文件上传实现全部示例,java文件上传
layui(谐音:类UI) 是一款采用自身模块规范编写的前端 UI 框架,遵循原生 HTML/CSS/JS 的书写与组织形式,门槛极低,拿来即用. layui文件上传示例地址:https://www. ...
- NOIP2002 字串变换题解(双向搜索)
65. [NOIP2002] 字串变换 时间限制:1 s 内存限制:128 MB [问题描述] 已知有两个字串A$, B$及一组字串变换的规则(至多6个规则): A1$ -> B1$ A2$ ...