AMCoder
AMCoder

Reputation: 793

How to overload unary & outside class?

You can overload the unary & operator inside a class as:

struct X
{
   void* operator &()
   {
      return this;
   }
};

so that it returns an address. How would you overload it outside of a class:

struct X
{
};

void* operator &(const X& x)
{
    //how?
}

Taking the address of the parameter would result in infinite recursion.

Upvotes: 3

Views: 413

Answers (1)

James Brock
James Brock

Reputation: 3426

In C++11, there is template< class T > T* std::addressof(T& arg).

std::addressof

You can also get the same function for C++03 from Boost Utility

Upvotes: 5

Related Questions