reference wrapper作用
声明于 <functional> 中的 class std::reference_wrapper<> 主要用来“喂 ” reference 给function template, 后者原本以 by value方式接受参数。对于一个给定类型 T ,这个 class 提供 ref () 用以隐式转换为 T& ,一个 cref () 用以隐式转换为 const T& ,这往往允许 function template 得以操作 reference 而不需要另写特化版本。
简单来说,就是让按值传参的模板可以接受一个引用作为参数。
例如,声明如下
template <typename T>
void foo (T val);
经由调用
int x;
foo(std::ref(x));
T变成int &,而经由调用
int x;
foo(std::cref(x));
T变成了const int &