exponent makes me think of Exp(x) = e^x
Anyway... seems like more trouble than it ever would be worth.
Code:
#include <cassert>
#include <cmath>
#include <iostream>
namespace power
{
struct mult_p
{
mult_p(unsigned int n_=0) : n(n_) {}
unsigned int n;
};
struct p
{
p(unsigned int n_=0) : n(n_), x(n_) {}
unsigned int n;
mult_p x;
const mult_p & operator *() const { return x; }
};
#define DECLARE_POWER(n) const p p##n(n)
#define DP DECLARE_POWER
DP(1); DP(2); DP(3); DP(4); DP(5); DP(6); DP(7); DP(8); DP(9); DP(10); DP(11); DP(12);
DP(13);DP(14);DP(15);DP(16);DP(17);DP(18);DP(19);DP(20);DP(21);DP(22); DP(23); DP(24);
#undef DP
#undef DECLARE_POWER
}//namespace power
template<class T>
T operator ^ (const T & left, const power::p & right)
{
if(!right.n) return T(1);
T ret = left;
for(unsigned int i = 1; i < right.n; ++i)
ret *= left;
return ret;
}
template<class T>
T operator * (const T & left, const power::mult_p & right)
{
if(!right.n) return T(1);
T ret = left;
for(unsigned int i = 1; i < right.n; ++i)
ret *= left;
return ret;
}
int main()
{
using namespace power;
int num = 23;
int x = std::pow(static_cast<double>(a),3);
int b = num**p3;
int c = num^p3;
int d = num**p(3);
int e = num^p(3);
std::cout << num << '\n'
<< x << '\n'
<< b << '\n'
<< c << '\n'
<< d << '\n'
<< e << std::endl;
}
The language just doesn't want to do it. It's too bad (in a superficial sense) that you can't define objects that function as operators. E++ will do the following:
Code:
template<class T>
class operator ** : precedence ++
{
T operator binary(const T & l, const unsigned int r)
{
T ret = l;
for(unsigned int i = 1; i < r; ++i)
ret *= l;
return ret;
}
void operator unary<arg_right>(const std::string & s)
{
std::cerr << "Urgent thing! " << s << std::endl;
}
};
using operator **;
int main()
{
std::cout << 2.334**7 << std::endl;
**"This would be so cool!";
unsigned int * ptr = new unsigned int(3);
std::cout << (2**ptr) << std::endl; //This would not be so cool....
//Well, as long as ptr wouldn't get cast into an unsigned int, we'd be ok.
}
Code:
template <class T>
class operator ^
{
T operator binary(T&l, const unsigned int r)
{ . . . . . }
};
int main()
{
using operator ^;
std::cout << 2^10 << std::endl;
operator ^ = default;
std::cout << std::hex << 0^0xF1 << std::endl;
}
Mass confusion would ensue.