Exponent operator overloading Saturday 2nd January 2010

In C++ you can’t create new operators to overload, you can only overload the operators that are already defined in the language. Often, an exponentiation operator is cited as an example of a new operator that you might want to have, so something like this isn’t possible.


#include <cmath>
#include <cassert>

int main()
{

    Double d1 = 81.0;
    Double d2 = 0.5;
    Double d3 = 4.0;
    Double d4 = 3.0;

    assert( d1 * d2 == 40.5 );
    assert( d1 ** d2 == 9.0 );
    assert( d4 ** d3 == d1 );
    assert( d4 * d3 == 12.0 );

    return 0;
}

(Excuse the use of == with floating point, in this toy example all the numbers have exact representations.)

Or is it?

Actually, it is. By suitable abuse of the prefix version of * and a simple proxy class we can get the effect of a ** operator although you might not always get the precedence that you expect.

#include <cmath>

template<class T>
struct Exponent
{
    explicit Exponent(T t)
        : val(t)
    {
    }

    T val;
};

template<class T>
class Number
{
public:

    Number(T t)
        : val(t)
    {
    }

    Exponent<T> operator*() const
    {
        return Exponent<T>(val);
    }

    Number operator*(const Exponent<T>& e) const
    {
        return Number(std::pow(val, e.val));
    }

    operator T() const
    {
        return val;
    }

private:

    T val;
};

typedef Number<double> Double;

Neat, if evil.

One Comments
Andy Balaam January 2nd, 2010

Convert to exponent, then apply exponent. It kind of makes sense.

I vote for more operator overloading evil.