views:

57

answers:

1

Inside boost there's boost::detail::addr_impl_ref struct that basically has a constructor accepting a T& reference and an overloaded operator T&() that returns that reference. It is used in the implementation of boost::addressof():

template<class T> T* addressof( T& v )
{
    return boost::detail::addressof_impl<T>::f( boost::detail::addr_impl_ref<T>( v ), 0 );
}

boost::detail::addressof_impl<T>::f() accepts T& as the first parameter. boost::addressof<T>() also has T& v as the parameter.

Why is boost::detail::addr_impl_ref() temporary object used here to store and return T& instead of just passing T& v?

+2  A: 

It prevents other implicit conversion operators of T to be a part of the conversion.

EDIT: For instance:

struct foo
{
   operator foo*()
   {
      return 0;
   }
};
dalle
Could you please provide an example of what could go wrong without using that function?
sharptooth
Do you mean that with the example provided boost::detail::addressof_impl<T>::f( T*) could be called? Is that the only problem possible?
sharptooth
Yes, without it the two `addressof_impl<T>::f` overloads have similar conversion, resulting in a compile time error.
dalle