Exercise 11.14.21

The text for this exercise reads:

(*2)

It is a pretty neat but simple thing. Just have 2**I be interpreted as 2*(*I). If Index::operator*() return a helper class and operator*(double, helper_class) is defined, it gets called. Or to put it in C++:

class Index
{
 double m_power;
 struct P { Index& x;
           P(Index& d):x(d) {}
         };

 friend double mypow(double, Index);
 friend double operator*(double, P);

 public:
 Index(double d = 0.0):m_power(d) {}
 P operator*() { return P(*this); }
};

double mypow(double arg, Index i)
{
 return pow(arg, i.m_power); // Just rely on standard  stuff
}


double operator *(double d, Index::P p)
{
 return mypow(d, p.x);
}

Now, if you have something like:

Index I(4.0);
double x = 2**I;
assert (x == 16);

The assert will not fail.

Back to the Exercise Page
Back to my Home Page 1