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

http://blog.csdn.net/zengraoli/article/details/9663057

class noncopyable{

void operator()(int){}

};

noncopyable n;

for_each(v.begin(), v.end(), boost::ref(n)); //---------------- not work!!!

for_each(v.begin(), v.end(), boost::bind<void>(boost::ref(n), _1));  //--------------------great!!!!!!



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

  1. #include "stdafx.h"  
  2. #include "boost/utility/result_of.hpp"  
  3. #include "boost/typeof/typeof.hpp"  
  4. #include "boost/assign.hpp"  
  5. #include "iostream"  
  6. using namespace std;  
  7. #include "vector"  
  8.   
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     struct square  
  13.     {  
  14.         typedef void result_type;  
  15.         void operator()(int& x)  
  16.         {  
  17.             x = x * x;  
  18.             cout << x << endl;  
  19.         }  
  20.     };  
  21.   
  22.     vector<int> v = (boost::assign::list_of(1), 2, 3, 4, 5);  
  23.     for_each (v.begin(), v.end(), square());  
  24.   
  25.     return 0;  
  26. }  

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

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


a、类介绍

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

  1. template<class T> class reference_wrapper  
  2. {   
  3. public:  
  4.     typedef T type;  
  5.   
  6. #if defined( BOOST_MSVC ) && BOOST_WORKAROUND( BOOST_MSVC, < 1300 )  
  7.   
  8.     explicit reference_wrapper(T& t): t_(&t) {}  
  9.   
  10. #else  
  11.   
  12.     explicit reference_wrapper(T& t): t_(boost::addressof(t)) {}  
  13.   
  14. #endif  
  15.   
  16.     operator T& () const { return *t_; }  
  17.   
  18.     T& get() const { return *t_; }  
  19.   
  20.     T* get_pointer() const { return t_; }  
  21.   
  22. private:  
  23.   
  24.     T* t_;  
  25. };  

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

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


b、基本用法

看一个例子:

  1. #include "stdafx.h"  
  2. #include "boost/utility/result_of.hpp"  
  3. #include "boost/typeof/typeof.hpp"  
  4. #include "boost/assign.hpp"  
  5. #include "boost/ref.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     int x = 10;  
  13.     reference_wrapper<int> rw(x);  
  14.     assert(x == rw);  
  15.     (int &)rw = 100;  
  16.     assert(x == 100);  
  17.   
  18.   
  19.     reference_wrapper<int> rw2(rw);  
  20.     assert(rw.get() == 100);  
  21.   
  22.     string str;  
  23.     boost::reference_wrapper<string> rws(str);  
  24.     *rws.get_pointer() = "zengraoli";  
  25.     cout << rws.get().size() << endl;  
  26.   
  27.   
  28.     return 0;  
  29. }  

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,例如:

  1. #include "stdafx.h"  
  2. #include "boost/utility/result_of.hpp"  
  3. #include "boost/typeof/typeof.hpp"  
  4. #include "boost/assign.hpp"  
  5. #include "boost/ref.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     double x = 1.9999l;  
  13.     BOOST_AUTO(rw, cref(x));  
  14.     cout << typeid(rw).name() << endl;  
  15.   
  16.     BOOST_AUTO(rw2, ref(x));  
  17.     cout << typeid(rw2).name() << endl;  
  18.   
  19.     return 0;  
  20. }  

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

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

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

  1. #include "stdafx.h"  
  2. #include "boost/utility/result_of.hpp"  
  3. #include "boost/typeof/typeof.hpp"  
  4. #include "boost/assign.hpp"  
  5. #include "boost/ref.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     double x = 5.0;  
  13.     cout << sqrt(boost::ref(x)) << endl;  
  14.   
  15.     return 0;  
  16. }  

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包装;

下面是代码:

  1. #include "stdafx.h"  
  2. #include "boost/utility/result_of.hpp"  
  3. #include "boost/typeof/typeof.hpp"  
  4. #include "boost/assign.hpp"  
  5. #include "boost/ref.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     vector<int> v(10, 2);  
  13.     BOOST_AUTO(rw, cref(v));  
  14. //  assert(boost::is_reference_wrapper<BOOST_TYPEOF(rw)>::value);  
  15.     assert(!boost::is_reference_wrapper<BOOST_TYPEOF(v)>::value);  
  16.   
  17.     string str;  
  18.     BOOST_AUTO(rws, ref(str));  
  19.     cout << typeid(boost::unwrap_reference<BOOST_TYPEOF(rws)>::type).name() << endl;  
  20.     cout << typeid(boost::unwrap_reference<BOOST_TYPEOF(str)>::type).name() << endl;  
  21.   
  22.     return 0;  
  23. }  

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

  1. #include "stdafx.h"  
  2. #include "boost/utility/result_of.hpp"  
  3. #include "boost/typeof/typeof.hpp"  
  4. #include "boost/assign.hpp"  
  5. #include "boost/ref.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. int _tmain(int argc, _TCHAR* argv[])  
  11. {  
  12.     set<int> s;  
  13.     BOOST_AUTO(rw, boost::ref(s));      // 获得一个包装对象  
  14.     boost::unwrap_ref(rw).insert(12);   // 直接解开包装  
  15.   
  16.     string str("zengraoli");  
  17.     BOOST_AUTO(rws, boost::cref(str));  // 获得一个常对象的包装  
  18.     cout << typeid(boost::unwrap_ref(rws)).name() << endl; // 解包装  
  19.   
  20.     return 0;  
  21. }  

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

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


e、综合使用

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

  1. #include "stdafx.h"  
  2. #include "boost/utility/result_of.hpp"  
  3. #include "boost/typeof/typeof.hpp"  
  4. #include "boost/assign.hpp"  
  5. #include "boost/ref.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. class BigClass  
  11. {  
  12. public:  
  13.     BigClass() : x(0)  
  14.     {  
  15.   
  16.     }  
  17.   
  18.     ~BigClass()  
  19.     {  
  20.   
  21.     }  
  22.   
  23.     void Print()  
  24.     {  
  25.         cout << "big class x value : " << ++x << endl;  
  26.     }  
  27.   
  28. private:  
  29.     int x;  
  30. };  
  31.   
  32.   
  33. template<typename T>  
  34. void Print(T a)  
  35. {  
  36.     for (int i = 0; i < 2; ++i)  
  37.     {  
  38.         boost::unwrap_ref(a).Print();  
  39.     }  
  40. }  
  41.   
  42.   
  43. int _tmain(int argc, _TCHAR* argv[])  
  44. {  
  45.     BigClass bigclass;  
  46.     BOOST_AUTO(rw, boost::ref(bigclass));  
  47.     bigclass.Print();  
  48.   
  49.     Print(bigclass);  
  50.     Print(rw);  
  51.     Print(bigclass);  
  52.     bigclass.Print();  
  53.   
  54.     return 0;  
  55. }  

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

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


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

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

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


  1. #include "stdafx.h"  
  2. #include "boost/utility/result_of.hpp"  
  3. #include "boost/typeof/typeof.hpp"  
  4. #include "boost/assign.hpp"  
  5. #include "boost/ref.hpp"  
  6. #include "iostream"  
  7. using namespace std;  
  8.   
  9.   
  10. struct square  
  11. {  
  12.     typedef void result_type;  
  13.     void operator()(int& x)  
  14.     {  
  15.         x = x * x;  
  16.         cout << x << endl;  
  17.     }  
  18. };  
  19.   
  20.   
  21. int _tmain(int argc, _TCHAR* argv[])  
  22. {  
  23.     typedef double (*pFunc)(double);  
  24.     pFunc pf = sqrt;  
  25.     cout << boost::ref(pf)(5.0) << endl;  
  26.   
  27.     square sq;  
  28.     int x = 5;  
  29.     boost::ref(sq)(x);  
  30.     cout << x << endl;  
  31.   
  32.     vector<int> v = (boost::assign::list_of(1), 2, 3, 4, 5);  
  33.     for_each (v.begin(), v.end(), boost::ref(sq));  
  34.   
  35.     return 0;  
  36. }  

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


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

  1. typename result_of<T()>::type operator()() const  
  2. {  
  3.     return (*t_)();  
  4. }  
  5.   
  6. template<typename T0>  
  7. typename result_of<T(T0)>::type operator()(T0 t0) const  
  8. {  
  9.     return (*t_)(t0);  
  10. }  
  11.   
  12. template<typename T0, typename T1>  
  13. typename result_of<T(T0, T1)>::type operator()(T0 t0, T1 t1) const  
  14. {  
  15.     return (*t_)(t0, t1);  
  16. }  


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


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


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


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值