c++ - span 可以是 constexpr 吗?

标签 c++ constexpr c++20

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/

相关文章:

c++ - constexpr std::optional 重置

c++ - 从转储中获取调用堆栈的几乎所有帧中的 this 指针 NULL 意味着什么?

c++ - 字符数组复制错误

c++ - 具有静态 constexpr 成员的模板类的 ODR

c++ - 如何在 C++11 constexpr 中检查 double 的位模式是 0x0?

C++ 20 概念中的依赖模板

c++ - 当变量是右值引用时自动从局部变量移动

具有动态内存分配的 C++ constexpr 函数

c++ - 从 VS2008 移植到 VS2013 时绑定(bind)错误 C2668

c++ xerces reference没有定义但已定义