function object研究之十一 addressof

來源:互聯網
上載者:User

來看看boost::detail::addr_impl_ref模板,在addressof.hpp檔案中:

template<class T> struct addr_impl_ref{    T & v_;    inline addr_impl_ref( T & v ): v_( v ) {}    inline operator T& () const { return v_; }private:    addr_impl_ref & operator=(const addr_impl_ref &);};

這個模板將建構函式的參數儲存到內部引用變數中,並禁止賦值操作,同時提供了T&類型轉換操作。下面是使用例子:

string str = "ok";boost::detail::addr_impl_ref<string> r(str);string & str2 = (string &)r;

再看看addressof_impl模板:

template<class T> struct addressof_impl{    static inline T * f( T & v, long )    {        return reinterpret_cast<T*>(            &const_cast<char&>(reinterpret_cast<const volatile char &>(v)));    }    static inline T * f( T * v, int )    {        return v;    }};

這個模板的建構函式接受T& v作為參數,並返回v的指標。注意,這裡碰到了非常奇怪的reinterpret_cast的連續使用,主要是為了防止T類型重載了operator & 導致行為未定義。這種奇怪的使用方式解決了這個問題,能夠獲得真是的v的地址。

可以參考相關問題的討論連結:http://stackoverflow.com/questions/1142607/if-an-operator-is-overloaded-for-a-c-class-how-could-i-use-a-default-operator

有了前兩個基礎,看看boost提供的非常有用的addressof模板:

template<class T> T * addressof( T & v ){#if defined( __BORLANDC__ ) && BOOST_WORKAROUND( __BORLANDC__, BOOST_TESTED_AT( 0x610 ) )    return boost::detail::addressof_impl<T>::f( v, 0 );#else    return boost::detail::addressof_impl<T>::f( boost::detail::addr_impl_ref<T>( v ), 0 );#endif}

現在可以總結下:

boost::addressof接受T& v,返回T指標。而且無需擔心T是否重載了自己的operator &.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.