如何解决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
元素的指针。
由于 arr
不是 static
,它位于堆栈中,因此在编译时无法确定其地址。
如果您使 arr
static
,它会起作用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。