Calculating power with C++ 11

suggest change

With C++11 and higher calculations at compile time can be much easier. For example calculating the power of a given number at compile time will be following:

template <typename T>
constexpr T calculatePower(T value, unsigned power) {
    return power == 0 ? 1 : value * calculatePower(value, power-1);
}

A constexpr function is evaluated at compile time when the call is a constant expression, for example when every argument is a constant expression. Otherwise it is an ordinary runtime call.

In C++11 a constexpr function body had to be a single return statement.

Unlike a template metafunction, the same function can also run at runtime. If an argument is not known at compile time (for example value is read from the user), the call runs at runtime, so you do not need a second implementation.

E.g.

void useExample() {
    constexpr int compileTimeCalculated = calculatePower(3, 3); // computes at compile time,
                               // as both arguments are known at compilation time
                               // and used for a constant expression.
    int value;
    std::cin >> value;
    int runtimeCalculated = calculatePower(value, 3);  // runtime calculated,
                                    // because value is known only at runtime.
}

Another way to calculate power at compile time can make use of fold expression as follows:

#include <iostream>
#include <utility>

template <class T, T V, T N, class I = std::make_integer_sequence<T, N>>
struct power;

template <class T, T V, T N, T... Is>
struct power<T, V, N, std::integer_sequence<T, Is...>> {
   static constexpr T value = (static_cast<T>(1) * ... * (V * static_cast<bool>(Is + 1)));
};

int main() {
   std::cout << power<int, 4, 2>::value << std::endl;
}

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents