I have the following very simple template. As I learned, ^
is not the exponential operator. Now I'm looking for a way to compute this power. There are many examples with a recursive template on the internet. This is not too difficult.
But I wonder: Is there actually no "built-in" method in C++ to compute this on compile time?
template <int DIM>
class BinIdx : Idx
{
static const int SIZE = 3 ^ DIM; // whoops, this is NOT an exponential operator!
}
As mentioned you can use <<
if the exponent is a power of two.
Otherwise, if the exponents are non-negative integers you can write a constexpr function like this one.
template<typename T, typename U>
auto constexpr pow(T base, U exponent) {
static_assert(std::is_integral<U>(), "exponent must be integral");
return exponent == 0 ? 1 : base * pow(base, exponent - 1);
}
This will obviously break for large exponents as well as negative ones, though.
I am not fully aware of how well compilers optimize function calls in constant expressions. Here's a manual optimization for cases where the exponents are powers of two. This will also reduce the amount of recursion done.
template<typename T>
bool constexpr is_power_of_two(T x) {
return (x != 0) && ((x & (x - 1)) == 0);
}
template<typename T, typename U>
auto constexpr pow(T base, U exponent) {
static_assert(std::is_integral<U>(), "exponent must be integral");
if (is_power_of_two(exponent)) {
return base << exponent;
}
return exponent == 0 ? 1 : base * pow(base, exponent - 1);
}
More efficient algorithms are also available. However, I am bad at computer science so I don't know how to implement them.