Question

I noticed that sample code for reference-type functions on the web and in books all have only a return line (like the following which is from MSDN)

class Point
{
public:
  unsigned& x();
private:
  unsigned obj_x;
};

unsigned& Point :: x()
{
  return obj_x;
}

int main()
{
  Point ThePoint;
  ThePoint.x() = 7;
}

I think if I include more lines (artithmetic expressions, control structures, etc) in a reference-type function, they will only change its behavior when it's used as a normal (R-value) function. But how could I write a function that, when used as an L-value, will do some arithmetic on its R-value (here the number 7) or checks it against some conditions, before putting it into the return variable (here obj_x)?

Was it helpful?

Solution

What you mean is very conterintuitive. But this can not be achived that way.

What you want is ordinary done with the help of proxy objects, like it is done in std::vector<bool> specialization. When you using it like v[i] = true;, v[i] returns proxy object, that have overloaded assignment operator, which rises ith bit in internal bit-string.

Example:

struct A
{
   struct proxy
   {
      proxy(int * x)
         : x_(x)
      {       
      }

      proxy & operator = (int v)
      {
         *x_ = v + 2;
         return *this;
      }

      operator int() const
      {
         return *x_;
      }
    private:
      int * x_;
   };

   proxy x_add_2()
   {
      return proxy(&x_);
   }

   int x() const
   {
      return x_;
   }
private:
   int x_;
};

int main(int argc, char* argv[])
{
   A a;
   a.x_add_2() = 2;
   std::cout << a.x() << std::endl;
   return 0;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top