我正在尝试初始化一个span<const T*>
- 即指向 const 数据的指针列表。但是,const
指针和span<>
可用构造函数之间的转换规则阻碍了我。
我确定有办法做到这一点,但我找不到正确的转换/调用。
旁白:我实际上没有使用 C++20,而是tcb::span,它使用较旧的P0122R7构造函数集,带有 (pointer,size) 而不是迭代器。但我怀疑在 C++20 上工作会让我朝着正确的方向前进。
下面的示例演示了我正在尝试做的事情,以及一些修复它的失败尝试:
#include<span>
#include<vector>
#include<iostream>
using std::cout;
using std::endl;
int main() {
int a = 0;
int b = 1;
int c = 2;
std::vector<int*> pointers = { &a, &b, &c };
// This declaration does not work; no span<> constructor matches it.
std::span<const int*> cspan(&pointers[0], pointers.size());
// This declaration also does not work; the cast is fine, but still no span<> constructor matches.
//std::span<const int*> cspan(static_cast<const int *const*>(&pointers[0]), pointers.size());
// This declaration works, but then "cspan" cannot be sorted, since
// the pointers themselves are const, and cannot be overwritten.
//std::span<const int* const> cspan(&pointers[0], pointers.size());
// Sort the span (by address)
// This is the code I want to work. I just need some way to declare 'cspan' properly.
std::sort(cspan.begin(), cspan.end());
return 0;
}
有任何想法吗?