首页 > 解决方案 > C++20 中的 constexpr 数学函数

问题描述

我正在尝试做类似的事情:

#include <cmath>

template <unsigned A, unsigned B>
struct fu {
    constexpr unsigned long power_A_of_B = std::pow(A, B);
};

但是编译器给出错误,因为pow()is not constexpr

为什么标题中的数学函数<cmath>不是constexpr?例如, log(), log2(), pow(), abs()and fmax()are notconstexpr但其他在<algorithm>are 中, 例如max(),min()和 `clamp()'。

标签: c++templatesconstexprc++20

解决方案


为什么标题中的数学函数不是 constexpr?

原因很好地隐藏在以下文档中std::pow

std::pow、std::powf、std::powl - cppreference.com

错误处理

按照 math_errhandling 中指定的方式报告错误。

请参阅math_errhandling的文档。

现在如何处理这个宏constexpr

所以整个问题是保持与旧规范的兼容性。

唯一可能的解决方案是使用替代实现。我发现了类似的东西,没有测试过,但看起来很有希望。在这里找到。


推荐阅读