T.123: Use constexpr functions to compute values at compile time
T.123:使用常量表达式函数在编译时求值
A function is the most obvious and conventional way of expressing the computation of a value. Often a constexpr function implies less compile-time overhead than alternatives.
函数是表达求值的最显然,最便利的方式。通常,常量表达式函数比其他选项需要的编译时代价更小。
Note(注意)
"Traits" techniques are mostly replaced by template aliases to compute types and constexpr functions to compute values.
“特征”技术用于计算类型时基本上已经模板别名所代替,用于求值时则可以用常量表达式函数代替。
Example(示例)
template<typename T>
// requires Number<T>
constexpr T pow(T v, int n) // power/exponential
{
T res = 1;
while (n--) res *= v;
return res;
}
constexpr auto f7 = pow(pi, 7);
原文链接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#t123-use-constexpr-functions-to-compute-values-at-compile-time