`

boost reference_wrapper

阅读更多
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就像是被包装对象的一个别名,但它只有在使用T的语境下才能够执行隐性转换,其他情况下则需要调用类型转换函数或get()函数才能真正被包装对象。
#include<boost/ref.hpp>
#include<assert.h>
#include<iostream>
using namespace std;
using namespace boost;
int main()
{
    int x=10;
    reference_wrapper<int> rw(x);
    assert(x==rw);
    (int &)rw=100;
    reference_wrapper<int> rw2(rw);
    assert(rw2.get()==100);
    cout << rw2.get() << endl;
    string str;
    reference_wrapper<string> rws(str);
    *rws.get_pointer() = "test reference_wrapper";
    cout << rws.get().size() << endl;
}

100
22
分享到:
评论

相关推荐

    C++中隐式类型转换学习笔记

    template&lt;typename _Tp&gt; class reference_wrapper : public _Reference_wrapper_base&lt;typename remove_cv&lt;_Tp&gt;::type&gt; { _Tp* _M_data; public: typedef _Tp type; reference_wrapper(_Tp& __indata) noexcept :...

    objref.rar_Boost

    在Boost库中,可能存在一种实现对象引用的机制,如`boost::reference_wrapper`,它可以封装一个对象的引用,并提供类似指针的操作。 描述中提到的“一个简单的对象引用的设计。没有用到stl”,意味着这个压缩包可能...

    模板元编程技术pdf

    - **整型外覆器和操作**:定义一个整型包装类`int_wrapper`,并为其提供加法运算符重载。 - **序列与迭代器**:利用模板元编程创建一个动态数组类`dynamic_array`,支持随机访问迭代器。 - **算法**:编写一个元算法...

    C-Cpp-注意事项:有关现代C ++,C ++ 11,C ++ 14和C ++ 17,Boost库,ABI,外部功能接口和参考卡的说明

    C ++纸莎草纸-有关现代C ++的C ++注释 该存储库包含有关moodern C ++,系统编程以及为C和C ++构建系统的注释和示例。 HTML版本-包含来自此资源库的所有注释,已编译为html:

    BobBuilder_app

    As you can see you get a very noticeable performance boost with the new Intel Core iX processors. Comparing B+tree and MGIndex For a measure of relative performance of a b+tree, Red/Black tree and ...

Global site tag (gtag.js) - Google Analytics