gpt4 book ai didi

c++ - span 可以是 constexpr 吗?

转载 作者:行者123 更新时间:2023-12-01 18:40:05 34 4
gpt4 key购买 nike

std::span 的所有构造函数都被声明为 constexpr,但是我似乎无法让它们中的任何一个在 constexpr 上下文中工作。取消注释下面的任何 constexpr 将导致编译错误。

#include <array>
#include <span>

int main()
{
constexpr int carray[3] = { 0, 1, 2 };
constexpr std::array<int, 3> array{ 0, 1, 2 };
using S = std::span<const int, 3>;

/*constexpr*/ S span1{ array.data(), 3 };
/*constexpr*/ S span2{array.begin(), array.end()};
/*constexpr*/ S span3{carray};
/*constexpr*/ S span4{array};
}

实际上是否可以创建 constexpr span 类型,因为当构造函数必须初始化指针或引用时,它们似乎永远无法在编译时求值?

最佳答案

您不能在这样的常量表达式中使用非静态函数局部变量。您需要地址稳定性,而这只能通过静态对象来实现。将代码修改为

constexpr std::array<int, 3> array{ 0, 1, 2 };
constexpr int carray[3] = { 0, 1, 2 };

int main()
{
using S = std::span<const int, 3>;

constexpr S span1{ array.data(), 3 };
constexpr S span2{array.begin(), array.end()};
constexpr S span3{carray};
constexpr S span4{array};
}

int main()
{
static constexpr std::array<int, 3> array{ 0, 1, 2 };
static constexpr int carray[3] = { 0, 1, 2 };
using S = std::span<const int, 3>;

constexpr S span1{ array.data(), 3 };
constexpr S span2{array.begin(), array.end()};
constexpr S span3{carray};
constexpr S span4{array};
}

允许您创建 constexpr std::span

关于c++ - span 可以是 constexpr 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58962120/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com