首页 技术 正文
技术 2022年11月14日
0 收藏 542 点赞 4,387 浏览 6635 个字

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

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. int _tmain(int argc, _TCHAR* argv[])
  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. vector<int> v = (boost::assign::list_of(1), 2, 3, 4, 5);
  20. for_each (v.begin(), v.end(), square());
  21. return 0;
  22. }

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

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

a、类介绍

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

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

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

注意,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. int _tmain(int argc, _TCHAR* argv[])
  9. {
  10. int x = 10;
  11. reference_wrapper<int> rw(x);
  12. assert(x == rw);
  13. (int &)rw = 100;
  14. assert(x == 100);
  15. reference_wrapper<int> rw2(rw);
  16. assert(rw.get() == 100);
  17. string str;
  18. boost::reference_wrapper<string> rws(str);
  19. *rws.get_pointer() = “zengraoli”;
  20. cout << rws.get().size() << endl;
  21. return 0;
  22. }

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. int _tmain(int argc, _TCHAR* argv[])
  9. {
  10. double x = 1.9999l;
  11. BOOST_AUTO(rw, cref(x));
  12. cout << typeid(rw).name() << endl;
  13. BOOST_AUTO(rw2, ref(x));
  14. cout << typeid(rw2).name() << endl;
  15. return 0;
  16. }

第一个输出的是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. int _tmain(int argc, _TCHAR* argv[])
  9. {
  10. double x = 5.0;
  11. cout << sqrt(boost::ref(x)) << endl;
  12. return 0;
  13. }

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

下面是代码:

[转]  boost——ref的使用(Boost程序库完全开发指南)读书笔记[转]  boost——ref的使用(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 “boost/ref.hpp”
  6. #include “iostream”
  7. using namespace std;
  8. int _tmain(int argc, _TCHAR* argv[])
  9. {
  10. vector<int> v(10, 2);
  11. BOOST_AUTO(rw, cref(v));
  12. //  assert(boost::is_reference_wrapper<BOOST_TYPEOF(rw)>::value);
  13. assert(!boost::is_reference_wrapper<BOOST_TYPEOF(v)>::value);
  14. string str;
  15. BOOST_AUTO(rws, ref(str));
  16. cout << typeid(boost::unwrap_reference<BOOST_TYPEOF(rws)>::type).name() << endl;
  17. cout << typeid(boost::unwrap_reference<BOOST_TYPEOF(str)>::type).name() << endl;
  18. return 0;
  19. }

自由函数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. int _tmain(int argc, _TCHAR* argv[])
  9. {
  10. set<int> s;
  11. BOOST_AUTO(rw, boost::ref(s));      // 获得一个包装对象
  12. boost::unwrap_ref(rw).insert(12);   // 直接解开包装
  13. string str(“zengraoli”);
  14. BOOST_AUTO(rws, boost::cref(str));  // 获得一个常对象的包装
  15. cout << typeid(boost::unwrap_ref(rws)).name() << endl; // 解包装
  16. return 0;
  17. }

直接对一个未包装的对象使用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. class BigClass
  9. {
  10. public:
  11. BigClass() : x(0)
  12. {
  13. }
  14. ~BigClass()
  15. {
  16. }
  17. void Print()
  18. {
  19. cout << “big class x value : ” << ++x << endl;
  20. }
  21. private:
  22. int x;
  23. };
  24. template<typename T>
  25. void Print(T a)
  26. {
  27. for (int i = 0; i < 2; ++i)
  28. {
  29. boost::unwrap_ref(a).Print();
  30. }
  31. }
  32. int _tmain(int argc, _TCHAR* argv[])
  33. {
  34. BigClass bigclass;
  35. BOOST_AUTO(rw, boost::ref(bigclass));
  36. bigclass.Print();
  37. Print(bigclass);
  38. Print(rw);
  39. Print(bigclass);
  40. bigclass.Print();
  41. return 0;
  42. }

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

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

为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. struct square
  9. {
  10. typedef void result_type;
  11. void operator()(int& x)
  12. {
  13. x = x * x;
  14. cout << x << endl;
  15. }
  16. };
  17. int _tmain(int argc, _TCHAR* argv[])
  18. {
  19. typedef double (*pFunc)(double);
  20. pFunc pf = sqrt;
  21. cout << boost::ref(pf)(5.0) << endl;
  22. square sq;
  23. int x = 5;
  24. boost::ref(sq)(x);
  25. cout << x << endl;
  26. vector<int> v = (boost::assign::list_of(1), 2, 3, 4, 5);
  27. for_each (v.begin(), v.end(), boost::ref(sq));
  28. return 0;
  29. }

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

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

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

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

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

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

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

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,993
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,507
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,350
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,135
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,768
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,845