來看看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 &.