用 C11(及更高)计算功率

在编译时使用 C++ 11 及更高版本的计算可以更容易。例如,在编译时计算给定数字的幂将如下:

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

关键字 constexpr 负责在编译时计算函数,然后才会满足所有要求(例如,参见 constexpr 关键字参考),例如在编译时必须知道所有参数。

注意:在 C++ 11 中,constexpr 函数必须仅由一个 return 语句组成。

优点:将此方法与编译时计算的标准方法进行比较,此方法对于运行时计算也很有用。这意味着,如果在编译时不知道函数的参数(例如,值和功率是通过用户给出的),则函数在编译时运行,因此不需要复制代码(因为我们将被强制用于较旧的 C++标准)。

例如

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.
}

Version >= C++ 17

在编译时计算功率的另一种方法可以使用 fold 表达式,如下所示:

#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;
}