constexpr使用标准库算法

使用 C++17/C++20 x64 gcc/clang 构建时,以下代码段会产生编译错误,而通过直接取消引用迭代器*std::max_element(std::begin(arr), std::end(arr))工作正常。关于为什么的任何想法?我还观察到了自 C++20 以来已成为 constexpr 的其他标准算法的类似行为,例如std::upper_bound

int main()
{
    constexpr std::array<int,5> arr = {1,2,3,4,5};
    constexpr auto it = std::max_element(std::begin(arr), std::end(arr));
}
source>:11:73: error: '(((std::array<int, 5>::const_pointer)(& arr.std::array<int, 5>::_M_elems)) + 16)' is not a constant expression
   11 |     constexpr auto it  = std::max_element(std::begin(arr), std::end(arr));
      |           

回答

it必须存储一个指向 的元素的指针arr

由于arris not static,它位于堆栈上,因此无法在编译时确定其地址。

如果你使arr static.

  • @user3882729 I'm not sure I'd say that. The `std::max_element` call *is* something that can be evaluated at compile-time, "on it's own". But the value resulting from that evaluation is subject to further tests when you try to use it to initialize a `constexpr` variable. The iterator, which has `&arr` "in" it does not pass unless `arr` is `static`, but the dereferenced value is atomic and does pass. The iterator "is `constexpr`" in the sense that it's allowed as an *intermediate* in `constexpr` computation, just not as the result.

以上是constexpr使用标准库算法的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>