STL和Boost中的算法和函数大量使用了函数对象作为判断式或谓词参数,而这些参数都是传值语义,算法或函数在内部保修函数对象的拷贝并使用,例如:

#include "stdafx.h"
#include "boost/utility/result_of.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assign.hpp"
#include "iostream"
using namespace std;
#include "vector" int _tmain(int argc, _TCHAR* argv[])
{
struct square
{
typedef void result_type;
void operator()(int& x)
{
x = x * x;
cout << x << endl;
}
}; vector<int> v = (boost::assign::list_of(1), 2, 3, 4, 5);
for_each (v.begin(), v.end(), square()); return 0;
}

一般情况下传值语义都是可行的,但也有很多特殊情况,作为参数的函数对象拷贝代价过高(具有复杂的内部状态),或者不希望拷贝对象(内部状态不应该被改变),甚至拷贝是不可行的(noncopyable、单件)。

boost.ref应用代理模式,引入对象引用的包装器概念解决了这个问题。

a、类介绍

ref库定义了一个很小很简单的引用类型的包装器,名字叫reference_wrapper,它的类摘要如下:

template<class T> class reference_wrapper
{
public:
typedef T type; #if defined( BOOST_MSVC ) && BOOST_WORKAROUND( BOOST_MSVC, < 1300 ) explicit reference_wrapper(T& t): t_(&t) {} #else explicit reference_wrapper(T& t): t_(boost::addressof(t)) {} #endif operator T& () const { return *t_; } T& get() const { return *t_; } T* get_pointer() const { return t_; } private: T* t_;
};

注意,reference_wrapper的构造函数被声明为explicit,因此必须在创建reference_wrapper对象时就赋值初始化,就像是使用一个引用类型的变量。

reference_wrapper还支持隐式类型转换,可以在需要的语境下返回存储的引用,因此它很像引用类型,能够在任何需要T出现的地方使用reference_wrapper。

b、基本用法

看一个例子:

#include "stdafx.h"
#include "boost/utility/result_of.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assign.hpp"
#include "boost/ref.hpp"
#include "iostream"
using namespace std; int _tmain(int argc, _TCHAR* argv[])
{
int x = 10;
reference_wrapper<int> rw(x);
assert(x == rw);
(int &)rw = 100;
assert(x == 100); reference_wrapper<int> rw2(rw);
assert(rw.get() == 100); string str;
boost::reference_wrapper<string> rws(str);
*rws.get_pointer() = "zengraoli";
cout << rws.get().size() << endl; return 0;
}

reference_wrapper<int>rw(x);在这里包装int类型的引用,assert(x==rw);隐式转换为int类型,assert(x==100);显式转换为int&类型,用于左值;boost::reference_wrapper<string>rws(str);包装字符串的引用

c、工厂函数

reference_wrapper的名字过长,声明引用包装对象很不方便,因而ref库提供了两个便捷的工厂函数ref()和cref(),可以通过参数类型推导很容易地构造reference_wrapper对象。

ref()和cref()会根据参数类型自动地推导生成正确的reference_wrapper<T>对象,ref()产生的类型是T,而cref()产生的类型是Tconst,例如:

#include "stdafx.h"
#include "boost/utility/result_of.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assign.hpp"
#include "boost/ref.hpp"
#include "iostream"
using namespace std; int _tmain(int argc, _TCHAR* argv[])
{
double x = 1.9999l;
BOOST_AUTO(rw, cref(x));
cout << typeid(rw).name() << endl; BOOST_AUTO(rw2, ref(x));
cout << typeid(rw2).name() << endl; return 0;
}

第一个输出的是double const---cref

第二个输出的是double const--- ref

因为reference_wrapper支持拷贝,因此ref()和cref()可以直接用在需要拷贝的语义的函数参数中,而不必专门使用一个reference_wrapper来暂存,例如:

#include "stdafx.h"
#include "boost/utility/result_of.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assign.hpp"
#include "boost/ref.hpp"
#include "iostream"
using namespace std; int _tmain(int argc, _TCHAR* argv[])
{
double x = 5.0;
cout << sqrt(boost::ref(x)) << endl; return 0;
}

d、操作包装

ref库运用模板元编程技术提供两个特征类is_reference_wrapper和unwrap_reference,用于检测reference_wrapper对象:

is_reference_wrapper<T>的bool成员变量value可以判断T是否为一个reference_wrapper;

unwrap_reference<T>的内部类型定义type表明了T的真实类型,无论它是否经过reference_wrapper包装;

下面是代码:

#include "stdafx.h"
#include "boost/utility/result_of.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assign.hpp"
#include "boost/ref.hpp"
#include "iostream"
using namespace std; int _tmain(int argc, _TCHAR* argv[])
{
vector<int> v(10, 2);
BOOST_AUTO(rw, cref(v));
// assert(boost::is_reference_wrapper<BOOST_TYPEOF(rw)>::value);
assert(!boost::is_reference_wrapper<BOOST_TYPEOF(v)>::value); string str;
BOOST_AUTO(rws, ref(str));
cout << typeid(boost::unwrap_reference<BOOST_TYPEOF(rws)>::type).name() << endl;
cout << typeid(boost::unwrap_reference<BOOST_TYPEOF(str)>::type).name() << endl; return 0;
}

自由函数unwrap_ref()为解开包装提供了简便的方法,他利用unwrap_reference<T>直接解开reference_wrapper的包装(如果有的话),返回被包装对象的引用,例如:

#include "stdafx.h"
#include "boost/utility/result_of.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assign.hpp"
#include "boost/ref.hpp"
#include "iostream"
using namespace std; int _tmain(int argc, _TCHAR* argv[])
{
set<int> s;
BOOST_AUTO(rw, boost::ref(s)); // 获得一个包装对象
boost::unwrap_ref(rw).insert(12); // 直接解开包装 string str("zengraoli");
BOOST_AUTO(rws, boost::cref(str)); // 获得一个常对象的包装
cout << typeid(boost::unwrap_ref(rws)).name() << endl; // 解包装 return 0;
}

直接对一个未包装的对象使用unwrap_ref()也是允许的,他将直接返回对象自身的引用:

cout << unwrap_ref(str)<< endl; // 对未包装对象解包装

e、综合使用

假设有一个类BigClass,他具有复杂的内部状态,构造、拷贝都具有很高的代价:

#include "stdafx.h"
#include "boost/utility/result_of.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assign.hpp"
#include "boost/ref.hpp"
#include "iostream"
using namespace std; class BigClass
{
public:
BigClass() : x(0)
{ } ~BigClass()
{ } void Print()
{
cout << "big class x value : " << ++x << endl;
} private:
int x;
}; template<typename T>
void Print(T a)
{
for (int i = 0; i < 2; ++i)
{
boost::unwrap_ref(a).Print();
}
} int _tmain(int argc, _TCHAR* argv[])
{
BigClass bigclass;
BOOST_AUTO(rw, boost::ref(bigclass));
bigclass.Print(); Print(bigclass);
Print(rw);
Print(bigclass);
bigclass.Print(); return 0;
}

这段代码演示了拷贝传参和引用传参的不同。当调用Print(bigclass)时是拷贝传参,因此bigclass在函数中被复制,它内部状态的变化不影响原对象,在函数调用完成后bigclass的内部值仍然为1。

但调用Print(rw);时由于使用了reference_wrapper的包装,函数拷贝的是reference_wrapper对象,在函数内部被解包装为原对象的引用,因此改变了原对象的内部状态。

f、为ref增加函数调用功能

ref将对象包装为引用语义,降低了复制的代价,使引用的行为更像对象(因为对象更有用更强大),可以让容器安全地持有被包装的引用对象,可以被称为是“智能引用”。

但很遗憾的是ref库没有提供韩式调用操作operator(),这使得我们无法包装一个函数对象的引用并传递给标准库算法,而实际上这并不是一件困难的事情(下面开始改造一下ref库),先看看如下代码:

#include "stdafx.h"
#include "boost/utility/result_of.hpp"
#include "boost/typeof/typeof.hpp"
#include "boost/assign.hpp"
#include "boost/ref.hpp"
#include "iostream"
using namespace std; struct square
{
typedef void result_type;
void operator()(int& x)
{
x = x * x;
cout << x << endl;
}
}; int _tmain(int argc, _TCHAR* argv[])
{
typedef double (*pFunc)(double);
pFunc pf = sqrt;
cout << boost::ref(pf)(5.0) << endl; square sq;
int x = 5;
boost::ref(sq)(x);
cout << x << endl; vector<int> v = (boost::assign::list_of(1), 2, 3, 4, 5);
for_each (v.begin(), v.end(), boost::ref(sq)); return 0;
}

这是不正确的,因为ref库并没有函数调用功能。

下面我们来改造ref库。打开ref.hpp,找到reference_wrapper类,加上如下部分:

	typename result_of<T()>::type operator()() const
{
return (*t_)();
} template<typename T0>
typename result_of<T(T0)>::type operator()(T0 t0) const
{
return (*t_)(t0);
} template<typename T0, typename T1>
typename result_of<T(T0, T1)>::type operator()(T0 t0, T1 t1) const
{
return (*t_)(t0, t1);
}

这里用result_of<T()>::type确定了一个无参函数调用的返回类型,还需要在前面加上关键字typename,让编译器知道type是一个类型而不是成员变量。另外operator()必须是const的,因为他不变动referen_wrapper类的状态。参看代码,还有另外的部分是使用成员模板函数重载,同样地我们可以实现带N个参数的函数调用。

这样我们就完成了ref增加函数调用的功能。但需要注意,函数调用依赖的是result_of的功能,因此referen_wrapper包装的对象类型可以是函数指针、函数引用、成员函数指针或函数对象。

对函数对象有特别的要求,简单来说,其内部必须有typedefresult_type,用来定义返回值类型,否则无法推导。

boost------ref的使用(Boost程序库完全开发指南)读书笔记的更多相关文章

  1. boost------signals2的使用2(Boost程序库完全开发指南)读书笔记

    1.应用于观察者模式 本小节将使用signals2开发一个完整的观察者模式示例程序,用来演示信号/插槽的用法.这个程序将模拟一个日常生活场景:客人按门铃,门铃响,护士开门,婴儿哭闹. Ring.h: ...

  2. boost------function的使用(Boost程序库完全开发指南)读书笔记

    function是一个函数对象的“容器”,概念上像是c/c++中函数指针类型的泛化,是一种“智能函数指针”.它以对象的形式封装了原始的函数指针或函数对象,能够容纳任意符合函数签名的可调用对象. 因此, ...

  3. boost------bind的使用(Boost程序库完全开发指南)读书笔记

    bind是c++98标准库中函数适配器bind1st/bind2nd的泛化和增强,可以适配任意的可调用类型,包括函数指针.函数引用.成员函数指针和函数对象. 1.工作原理 bind并不是一个单独的类或 ...

  4. boost------signals2的使用1(Boost程序库完全开发指南)读书笔记

    signals2基于Boost的另一个库signals,实现了线程安全的观察者模式.在signals2库中,观察者模式被称为信号/插槽(signals and slots),他是一种函数回调机制,一个 ...

  5. boost------asio库的使用2(Boost程序库完全开发指南)读书笔记

    网络通信 asio库支持TCP.UDP.ICMP通信协议,它在名字空间boost::asio::ip里提供了大量的网络通信方面的函数和类,很好地封装了原始的Berkeley Socket Api,展现 ...

  6. [转] boost------ref的使用(Boost程序库完全开发指南)读书笔记

    http://blog.csdn.net/zengraoli/article/details/9663057 STL和Boost中的算法和函数大量使用了函数对象作为判断式或谓词参数,而这些参数都是传值 ...

  7. boost------asio库的使用1(Boost程序库完全开发指南)读书笔记

    asio库基于操作系统提供的异步机制,采用前摄器设计模式(Proactor)实现了可移植的异步(或者同步)IO操作,而且并不要求多线程和锁定,有效地避免了多线程编程带来的诸多有害副作用. 目前asio ...

  8. Ngine X 完全开发指南 读书笔记-前言

    一开始接触的编程语言是VF,那是一种可视化编程语言,所谓的可视化,就是运行结果能直接看得到的,非常直观,便于调试,适合刚刚接触编程的新人学习.当时学得懵懂,半知半解,就是感觉程序非常神奇,常常几句代码 ...

  9. node.js开发指南读书笔记(1)

    3.1 开始使用Node.js编程 3.1.1 Hello World 将以下源代码保存到helloworld.js文件中 console.log('Hello World!'); console.l ...

随机推荐

  1. 【关节点+桥】关节点和桥模板 Tarjan

    #include <cstdio> #include <cstring> #include <algorithm> using namespace std; con ...

  2. 我的MYSQL学习心得(六)

    原文:我的MYSQL学习心得(六) 我的MYSQL学习心得(六) 我的MYSQL学习心得(一) 我的MYSQL学习心得(二) 我的MYSQL学习心得(三) 我的MYSQL学习心得(四) 我的MYSQL ...

  3. opencv2对于读书笔记——二值化——thresholded功能

    opencv二进制图象值功能threshold功能 其结构 double cv::threshold( //二值化函数 const CvArr* src, //原始图像 CvArr* dst, //输 ...

  4. php+flash头像上传组件

    有会员系统的站点一般都会有一个头像上传组件,一般做的最简单的是 这样的方式长处是代码写的简单,仅仅要推断图片大小和类型,然后更新数据库.可是用户体验不高.并且站点其它页面假设要使用较小的20X20或1 ...

  5. android 应用程序框架

    携带Android软件开发时间,由开发商开发Android应用程序是通过应用程序框架和Android底层交互,因此,发展以达到最大的部分是应用程序框架. 应用集成框架 那里4一个重要组成部分,以下. ...

  6. js手机对应的多级导航分享

    js移动导航对应,您可以使用自适应时屏幕,当小画面在一定程度上的网站.使导航出现,The navigation effects such as the following figures:多级导航! ...

  7. php_ThinkPHP的RBAC(基于角色权限控制)详解

    一.什么是RBAC 基于角色的访问控制(Role-Based Access Control)作为传统访问控制(自主访问,强制访问)的有前景的代替受到广泛的关注. 在RBAC中,权限与角色相关联,用户通 ...

  8. 教你一步一步部署.net免费空间OpenShift系列之二------创建应用

    接上回书,注册完毕后需要在Openshift上创建一个应用空间,如如何创建空间呢,Openshift本身是不直接支持Mono来部署ASP.Net程序的,需要借助openshift-community- ...

  9. 使用Jenkins来构建Docker容器

    使用Jenkins来构建Docker容器(Ubuntu 14.04) 当开发更新了代码,提交到Gitlab上,然后由测试人员触发Jenkins,于是一个应用的新版本就被构建了.听起来貌似很简单,dua ...

  10. Python - 字符串的替换(interpolation) 具体解释

    字符串的插值(interpolation) 具体解释 本文地址: http://blog.csdn.net/caroline_wendy/article/details/27054263 字符串的替换 ...