引用传参与reference_wrapper
本文是<functional>
系列的第3篇。
引用传参
我有一个函数:
void modify(int& i)
{
++i;
}
因为参数类型是int&
,所以函数能够修改传入的整数,而非其拷贝。
然后我用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
:
int j = 1;
auto g = std::bind(modify, std::ref(j));
g();
std::cout << j << std::endl;
std::ref(j)
返回的就是std::reference_wrapper<int>
对象。
reference_wrapper
std::reference_wrapper
及其辅助函数大致长成这样:
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
方法获得其内部的引用。
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() }; }
最后组装一下就好啦!
引用传参与reference_wrapper的更多相关文章
- C++二级指针和指针引用传参
前提 一级指针和引用 已经清晰一级指针和引用. 可参考:指针和引用与及指针常量和常量指针 或查阅其他资料. 一级指针和二级指针 个人觉得文字描述比较难读懂,直接看代码运行结果分析好些,如果想看文字分析 ...
- Js 赋值传值和引用传址
赋值传值和引用传址 在JavaScript中基本数据类型都是赋值传值,复合数据类型都是引用传址(传地址) 基本数据类型的变量名和数据是直接存在"快速内存"(栈内存)中,而复合数据类 ...
- Go 到底有没有引用传参(对比 C++ )
Go 到底有没有引用传参(对比 C++ ) C++ 中三种参数传递方式 值传递: 最常见的一种传参方式,函数的形参是实参的拷贝,函数中改变形参不会影响到函数外部的形参.一般是函数内部修改参数而又不希望 ...
- js学习笔记<拷贝传值,引用传址和匿名函数>
拷贝传值:把一个变量的值拷贝一份,传给了另外一个变量拷贝传值中,两个变量之间没有任何联系,修改其中一个一个变量的值,原来的变量不变. 例: var arr1 = ["张三",24, ...
- Python中的引用传参
Python中函数参数是引用传递(注意不是值传递).对于不可变类型,因变量不能修改,所以运算不会影响到变量自身:而对于可变类型来说,函数体中的运算有可能会更改传入的参数变量. 引用传参一: >& ...
- [ 随手记6 ] C/C++ 形参、实参、按值传参、指针传参、引用传参
个人原创: 1. 形参:形式上的参数,一般多在函数声明.函数定义的参数上: 2. 实参:实体参数,有实际的值,在运算上被循环使用的值: 3. 按值传参:按值,就是把实际的值传给函数内部: 4. 指针传 ...
- &符号 (弃用引用传参了,不要用!!)
写法一 $age = function grow($age) { $age += ; return $age; } echo grow($age) echo $age 写法二 $age = funct ...
- Java中的new关键字和引用传参
先看看Java中如何使用new关键字创建一个对象的. [java] view plain copy public class Student { public String name; public ...
- c++拷贝构造函数引用传参
看一道C++面试题: 给出下述代码,分析编译运行的结果,并提供3个选项: A.编译错误 B.编译成功,运行时程序崩溃 C.编译运行正常,输出10 class A { private: int va ...
随机推荐
- CompletableFuture异步编排
什么是CompletableFuture CompletableFuture是JDK8提供的Future增强类.CompletableFuture异步任务执行线程池,默认是把异步任务都放在ForkJo ...
- 四、用户交互(输入input,格式化输出)与运算符
1.接收用户的输入 在Python3:input会将用户输入的所有内容都存成字符串类型 列: username = input("请输入您的账号:") # "egon&q ...
- Data Management and Data Management Tools
Data Management ObjectivesBy the end o this module, you should understand the fundamentals of data m ...
- Linux - 文件的三种时间之atime、ctime、mtime的区别和简单用法
在Linux中,文件或者目录中有三个时间属性 atime ctime mtime 简名 全名 中文 作用 atime Access Time 访问时间 最后一次访问文件(读取或执行)的时间 ctime ...
- Vue2.0 -- 钩子函数/ 过度属性/常用指令/以及Vue-resoure发送请求
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- Arcgis License的安装及破解
1.双击LicenseManager安装目录下的Setup.exe. 2.点击“Next”. 3.选择“I accept the license agreement”,点击“Next”. 4.点击“C ...
- Web Scraper 性能测试 (-_-)
刚在研究 Python 爬虫的时候,看到了个小白工具,叫 Web Scraper,于是来测试下好不好用. Web Scraper 是什么? 它是一个谷歌浏览器的插件, 用于批量抓取网页信息, 主要特点 ...
- minIO分布式集群搭建+nginx负载均衡
暂时关闭防火墙 systemctl stop firewalld 查看防火墙状态 systemctl status firewalld 赋予最高权限 chmod +x minio !/bin/bash ...
- U - Inviting Friends HDU - 3244(二分答案 + 完全背包)
U - Inviting Friends HDU - 3244 You want to hold a birthday party, inviting as many friends as possi ...
- PHP的运行方式(SAPI)
PHP 常量 PHP_SAPI 具有和 php_sapi_name() 相同的值. define('IS_CGI',(0 === strpos(PHP_SAPI,'cgi') || false !== ...