Exponential Operator in C++

Viewed 51797

I am taking a class in C++ and I noticed there are only a few math operators to use. I also noticed that C++ does not come with an exponential operator within its math library.

Why must one always write a function for this? Is there a reason for the makers of C++ to omit this operator?

4 Answers

Python has the ** operator for exponentiation. In C++ you can actually define an operator like that with some trickery. By combining the unary * operator with the binary * operator, like this:

#include <cmath>
#include <iostream>

struct Num {
    double value;

    Num(double value) : value(value) { }

    typedef Num* HalfStar;

    HalfStar operator*() const { return HalfStar(this); }
    Num operator*(const HalfStar& rhs) const
    {
        return Num(std::pow(value, rhs->value));
    }
    Num operator*(const Num& rhs) const
    {
        return Num(value * rhs.value);
    }

    friend std::ostream& operator<<(std::ostream& os, const Num& n)
    {
        return os << n.value;
    }
};

int main(int argc, char**argv)
{
    Num a = 10;
    Num b = 9;

    std::cout << "a*b = " << (a*b) << "\n";
    std::cout << "a**b = " << (a**b) << "\n";

    return 0;
}

This will not work with non-class types though, so you can not do: x**2.

See here for a live example.

Related