如何存储std::mdspan?

问题描述 投票:0回答:1

如果我想将

std::mdspan
的实例存储在要传递给函数的结构中,有没有办法在不将客户端函数转换为模板的情况下实现此目的?

在此代码中演示

#include <iostream>
#include <vector>
#include <mdspan>

int* dummy;

struct Container {
    decltype(std::mdspan(dummy, 0, 0)) array2d;
};

void foo(Container cont) {
    std::cout << cont.array2d[std::array{ 1, 1 }];
}

int main()
{
    std::vector<int> v = { 0, 1, 2, 3, 4, 5, 6, 7 };

    auto array2d = std::mdspan(v.data(), 2, 4);

    Container container;

    container.array2d = array2d;

    foo(container);
}

我不知道如何避免这个

dummy
对象来获取
std::mdspan
的类型,以及是否可以避免在
decltype
中使用
Container

decltype
替换为

std::mdspan<float*,int,int> array2d;

不适用于:

Z:/compilers/msvc/14.41.33923-14.41.33923.0/include\mdspan(1075): error C2903: 'mapping': symbol is neither a class template nor a function template Z:/compilers/msvc/14.41.33923-14.41.33923.0/include\mdspan(1075): note: the template instantiation context (the oldest one first) is <source>(6): note: see reference to class template instantiation 'std::mdspan<float *,int,int,std::default_accessor<float *>>' being compiled Z:/compilers/msvc/14.41.33923-14.41.33923.0/include\mdspan(1159): note: see reference to class template instantiation 'std::_Mdspan_mapping_base<_Extents,_LayoutPolicy>' being compiled with [ _Extents=int, _LayoutPolicy=int ] etc...
    
c++ std mdspan
1个回答
1
投票
您只需要填写

mdspan

的前2个参数,第一个是基础类型(这里是
int
),第二个是它的
extents

如果您在编译时知道 mdspan 大小,则可以将其编码到类型中,这使得速度更快

std::extents<size_t, 2, 4>

(注意:
size_t
此处表示索引是使用
size_t
完成的)。

如果只知道运行时的大小,然后使用动态范围来确定运行时的范围,则只需指定维度数

std::dextents<size_t,2>

(注意
d
中的
dextents
表示动态)

struct Container { std::mdspan<int, std::dextents<size_t,2>> array2d; };
    
© www.soinside.com 2019 - 2024. All rights reserved.