c++ - span 可以是 constexpr 吗?
问题描述
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 跨度类型,因为当构造函数必须初始化指针或引用时,它们似乎永远无法在编译时进行评估?
解决方案
您不能在这样的常量表达式中使用非静态函数局部变量。您需要地址稳定性,而这只能通过静态对象来实现。修改代码为
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
.
推荐阅读
- php - 字段列表中的PHP未知列但表存在
- python - 有没有办法在输入字段的 tkinter 应用程序上添加弹出屏幕键盘
- visual-studio-code - 启用“accessibilityModeEnabled”时如何启用“cursorWordLeftselect”和“cursorWordEndRightselect”
- java - 如何检查 Json 数组中是否存在密钥
- css - 滑块图像不会根据屏幕大小进行调整
- python - 如何通过表单 ValidationError 返回可用时隙列表
- html - 如何根据另一个 div 底部位置配置 div 位置?
- pandas - 减少熊猫数据透视表中的小数
- sql - SQL 为什么在按年排序时将获胜者放在最后?
- node.js - 续集错误:无法读取未定义的属性(读取“toString”)