如何初始化std::span<const T*>?常量问题

How to initialize std::span<const T*>? Problems with const-ness

我正在尝试初始化一个 span<const T*> — 即指向 const 数据的指针列表。 但是,const 指针之间的转换规则和 span<> 的可用构造函数阻碍了我。

我确定有办法做到这一点,但我找不到合适的 casting/invocation。

旁白:我实际上没有使用 C++20,而是 tcb::span, which uses the older P0122R7 组构造函数,使用 (pointer,size) 而不是迭代器。但我怀疑在 C++20 上工作会让我朝着正确的方向前进。

下面的例子演示了我正在尝试做的事情,以及一些修复它的失败尝试:

Live link on Godbolt

#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;
}

有什么想法吗?

有什么问题:

#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 };

    std::span<const int*> cspan(const_cast<const int**>(pointers.data()), pointers.size());

    std::sort(cspan.begin(), cspan.end());
    
    return 0;
}