本文是<functional>
系列的第3篇。html
我有一個函數:數組
void modify(int& i) { ++i; }
由於參數類型是int&
,因此函數可以修改傳入的整數,而非其拷貝。app
而後我用std::bind
把它和一個int
綁定起來:函數
int i = 1; auto f = std::bind(modify, i); f(); std::cout << i << std::endl;
但是i
仍是1
,爲何呢?原來std::bind
會把全部參數都拷貝,即便它是個左值引用。因此modify
中修改的變量,其實是std::bind
返回的函數對象中的一個int
,並不是原來的i
。工具
咱們須要std::reference_wrapper
:ui
int j = 1; auto g = std::bind(modify, std::ref(j)); g(); std::cout << j << std::endl;
std::ref(j)
返回的就是std::reference_wrapper<int>
對象。this
std::reference_wrapper
及其輔助函數大體長成這樣:spa
template<typename T> class reference_wrapper { public: template<typename U> reference_wrapper(U&& x) : ptr(std::addressof(x)) { } reference_wrapper(const reference_wrapper&) noexcept = default; reference_wrapper& operator=(const reference_wrapper& x) noexcept = default; constexpr operator T& () const noexcept { return *ptr; } constexpr T& get() const noexcept { return *ptr; } template<typename... Args> auto operator()(Args&&... args) const { return get()(std::forward<Args>(args)...); } private: T* ptr; }; template<typename T> reference_wrapper<T> ref(T& t) noexcept { return reference_wrapper<T>(t); } template<typename T> reference_wrapper<T> ref(reference_wrapper<T> t) noexcept { return t; } template<typename T> void ref(const T&&) = delete; template<typename T> reference_wrapper<const T> cref(const T& t) noexcept { return reference_wrapper<const T>(t); } template<typename T> reference_wrapper<const T> cref(reference_wrapper<T> t) noexcept { return reference_wrapper<const T>(t.get()); } template<typename T> void cref(const T&&) = delete;
可見,std::reference_wrapper
不過是包裝一個指針罷了。它重載了operator T&
,對象能夠隱式轉換回原來的引用;它還重載了operator()
,包裝函數對象時能夠直接使用函數調用運算符;調用其餘成員函數時,要先用get
方法得到其內部的引用。3d
std::reference_wrapper
的意義在於:指針
引用不是對象,不存在引用的引用、引用的數組等,但std::reference_wrapper
是,使得定義引用的容器成爲可能;
模板函數沒法辨別你在傳入左值引用時的意圖是傳值仍是傳引用,std::ref
和std::cref
告訴那個模板,你要傳的是引用。
儘管std::reference_wrapper
的簡單(可是不完整的)實現能夠在50行之內完成,GCC的標準庫爲了實現一個完美的std::reference_wrapper
仍是花了300多行(還不包括std::invoke
),其中200多行是爲了定義result_type
、argument_type
、first_argument_type
和second_argument_type
這幾個在C++17中廢棄、C++20中移除的成員類型。若是你是在C++20徹底普及之後讀到這篇文章的,就當考古來看吧!
定義這些類型所用的工具是繼承,一種特殊的、沒有「is-a」含義的public
繼承。以_Maybe_unary_or_binary_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; }; 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> { };
而後std::function<Res(Args...)>
去繼承_Maybe_unary_or_binary_function<Res, Args...>
:當sizeof...(Args) == 1
時繼承到std::unary_function
,定義argument_type
;當sizeof...(Args) == 2
時繼承到std::binary_function
,定義first_argument_type
和second_argument_type
;不然繼承一個空的_Maybe_unary_or_binary_function
,什麼定義都沒有。
各類模板技巧,tag dispatching、SFINAE等,面對這種需求都一籌莫展,只有繼承管用。
template<typename _Signature> struct _Mem_fn_traits; template<typename _Res, typename _Class, typename... _ArgTypes> struct _Mem_fn_traits_base { using __result_type = _Res; using __maybe_type = _Maybe_unary_or_binary_function<_Res, _Class*, _ArgTypes...>; using __arity = integral_constant<size_t, sizeof...(_ArgTypes)>; }; #define _GLIBCXX_MEM_FN_TRAITS2(_CV, _REF, _LVAL, _RVAL) \ template<typename _Res, typename _Class, typename... _ArgTypes> \ struct _Mem_fn_traits<_Res (_Class::*)(_ArgTypes...) _CV _REF> \ : _Mem_fn_traits_base<_Res, _CV _Class, _ArgTypes...> \ { \ using __vararg = false_type; \ }; \ template<typename _Res, typename _Class, typename... _ArgTypes> \ struct _Mem_fn_traits<_Res (_Class::*)(_ArgTypes... ...) _CV _REF> \ : _Mem_fn_traits_base<_Res, _CV _Class, _ArgTypes...> \ { \ using __vararg = true_type; \ }; #define _GLIBCXX_MEM_FN_TRAITS(_REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2( , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(const , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(volatile , _REF, _LVAL, _RVAL) \ _GLIBCXX_MEM_FN_TRAITS2(const volatile, _REF, _LVAL, _RVAL) _GLIBCXX_MEM_FN_TRAITS( , true_type, true_type) _GLIBCXX_MEM_FN_TRAITS(&, true_type, false_type) _GLIBCXX_MEM_FN_TRAITS(&&, false_type, true_type) #if __cplusplus > 201402L _GLIBCXX_MEM_FN_TRAITS(noexcept, true_type, true_type) _GLIBCXX_MEM_FN_TRAITS(& noexcept, true_type, false_type) _GLIBCXX_MEM_FN_TRAITS(&& noexcept, false_type, true_type) #endif #undef _GLIBCXX_MEM_FN_TRAITS #undef _GLIBCXX_MEM_FN_TRAITS2
_Mem_fn_traits
是成員函數類型的特徵(trait)類型,定義了__result_type
、__maybe_type
、__arity
和__vararg
成員類型:__arity
表示元數,__vararg
指示成員函數類型是不是可變參數的(如std::printf
,非變參模板)。... ...
中的前三個點表示變參模板,後三個點表示可變參數,參考:What are the 6 dots in template parameter packs?
成員函數類型有const
、volatile
、&
/&&
、noexcept
(C++17開始noexcept
成爲函數類型的一部分)4個維度,共24種,單獨定義太麻煩,因此用了宏。
一個類模板,當模板參數的類型定義了成員類型result_type
時該類模板也定義它,不然不定義它,如何實現?我剛剛新學到一種方法,用void_t
(即__void_t
)。
void_t
的定義出奇地簡單:
template<typename...> using void_t = void;
不就是一個void
嘛,有什麼用呢?請看:
template<typename _Functor, typename = __void_t<>> struct _Maybe_get_result_type { }; template<typename _Functor> struct _Maybe_get_result_type<_Functor, __void_t<typename _Functor::result_type>> { typedef typename _Functor::result_type result_type; };
第二個定義是第一個定義的特化。當_Functor
類型定義了result_type
時,兩個都正確,可是第二個更加特化,匹配到第二個,傳播result_type
;反之,第二個在實例化過程當中發生錯誤,根據SFINAE,匹配到第一個,不定義result_type
。
void_t
的技巧,本質上仍是SFINAE。
如下兩個類同理:
template<typename _Tp, typename = __void_t<>> struct _Refwrap_base_arg1 { }; template<typename _Tp> struct _Refwrap_base_arg1<_Tp, __void_t<typename _Tp::argument_type>> { typedef typename _Tp::argument_type argument_type; }; template<typename _Tp, typename = __void_t<>> struct _Refwrap_base_arg2 { }; template<typename _Tp> struct _Refwrap_base_arg2<_Tp, __void_t<typename _Tp::first_argument_type, typename _Tp::second_argument_type>> { typedef typename _Tp::first_argument_type first_argument_type; typedef typename _Tp::second_argument_type second_argument_type; };
#if __cpp_noexcept_function_type #define _GLIBCXX_NOEXCEPT_PARM , bool _NE #define _GLIBCXX_NOEXCEPT_QUAL noexcept (_NE) #else #define _GLIBCXX_NOEXCEPT_PARM #define _GLIBCXX_NOEXCEPT_QUAL #endif /** * Base class for any function object that has a weak result type, as * defined in 20.8.2 [func.require] of C++11. */ template<typename _Functor> struct _Weak_result_type_impl : _Maybe_get_result_type<_Functor> { }; /// Retrieve the result type for a function type. template<typename _Res, typename... _ArgTypes _GLIBCXX_NOEXCEPT_PARM> struct _Weak_result_type_impl<_Res(_ArgTypes...) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a varargs function type. template<typename _Res, typename... _ArgTypes _GLIBCXX_NOEXCEPT_PARM> struct _Weak_result_type_impl<_Res(_ArgTypes......) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a function pointer. template<typename _Res, typename... _ArgTypes _GLIBCXX_NOEXCEPT_PARM> struct _Weak_result_type_impl<_Res(*)(_ArgTypes...) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; /// Retrieve the result type for a varargs function pointer. template<typename _Res, typename... _ArgTypes _GLIBCXX_NOEXCEPT_PARM> struct _Weak_result_type_impl<_Res(*)(_ArgTypes......) _GLIBCXX_NOEXCEPT_QUAL> { typedef _Res result_type; }; // Let _Weak_result_type_impl perform the real work. template<typename _Functor, bool = is_member_function_pointer<_Functor>::value> struct _Weak_result_type_memfun : _Weak_result_type_impl<_Functor> { }; // A pointer to member function has a weak result type. template<typename _MemFunPtr> struct _Weak_result_type_memfun<_MemFunPtr, true> { using result_type = typename _Mem_fn_traits<_MemFunPtr>::__result_type; }; // A pointer to data member doesn't have a weak result type. template<typename _Func, typename _Class> struct _Weak_result_type_memfun<_Func _Class::*, false> { }; /** * Strip top-level cv-qualifiers from the function object and let * _Weak_result_type_memfun perform the real work. */ template<typename _Functor> struct _Weak_result_type : _Weak_result_type_memfun<typename remove_cv<_Functor>::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 : _Weak_result_type<_Tp>, _Refwrap_base_arg1<_Tp>, _Refwrap_base_arg2<_Tp> { }; // - a function type (unary) template<typename _Res, typename _T1 _GLIBCXX_NOEXCEPT_PARM> struct _Reference_wrapper_base<_Res(_T1) _GLIBCXX_NOEXCEPT_QUAL> : 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 _GLIBCXX_NOEXCEPT_PARM> struct _Reference_wrapper_base<_Res(_T1, _T2) _GLIBCXX_NOEXCEPT_QUAL> : 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 _GLIBCXX_NOEXCEPT_PARM> struct _Reference_wrapper_base<_Res(*)(_T1) _GLIBCXX_NOEXCEPT_QUAL> : unary_function<_T1, _Res> { }; // - a function pointer type (binary) template<typename _Res, typename _T1, typename _T2 _GLIBCXX_NOEXCEPT_PARM> struct _Reference_wrapper_base<_Res(*)(_T1, _T2) _GLIBCXX_NOEXCEPT_QUAL> : binary_function<_T1, _T2, _Res> { }; template<typename _Tp, bool = is_member_function_pointer<_Tp>::value> struct _Reference_wrapper_base_memfun : _Reference_wrapper_base<_Tp> { }; template<typename _MemFunPtr> struct _Reference_wrapper_base_memfun<_MemFunPtr, true> : _Mem_fn_traits<_MemFunPtr>::__maybe_type { using result_type = typename _Mem_fn_traits<_MemFunPtr>::__result_type; };
不說了,看圖:
個人感覺:
template<typename _Tp> class reference_wrapper : public _Reference_wrapper_base_memfun<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&) = default; reference_wrapper& operator=(const reference_wrapper&) = default; 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 std::__invoke(get(), std::forward<_Args>(__args)...); } }; template<typename _Tp> inline reference_wrapper<_Tp> ref(_Tp& __t) noexcept { return reference_wrapper<_Tp>(__t); } 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; template<typename _Tp> inline reference_wrapper<_Tp> ref(reference_wrapper<_Tp> __t) noexcept { return __t; } template<typename _Tp> inline reference_wrapper<const _Tp> cref(reference_wrapper<_Tp> __t) noexcept { return { __t.get() }; }
最後組裝一下就好啦!