std ::未知大小的数组作为类成员

use*_*993 2 c++ arrays

我正在制作一个N维图像格式,我想将原始数据存储在一个

std::array<T, multiple of all dimensions>* where T is the type of single channel pixel value
Run Code Online (Sandbox Code Playgroud)

我希望构造函数采用像{20,30,50}这样的通道数组来制作一个20x30x50的位图,这样可以使数据的总长度为30000.最后,我希望能够像这样声明通道

auto* channelRed = new Channel<uint32_t>({20, 30, 50});
Run Code Online (Sandbox Code Playgroud)

问题是std :: array需要在模板参数中传递大小,这会在我的N维计划中引发一个问题.

如何在我的类中将std :: array指针设置为类字段,以便在构造函数执行期间定义数组的长度?

PS!是的,我知道我可以很容易地使用一个常规阵列,这就是我现在正在做的事情.我只想弄清楚什么是std :: array是有益的.

Bar*_*rry 7

你不能.一个std::array必须知道它在编译时的大小.这是该类型的一部分!A std::array<int, 2>和a std::array<int, 3>不仅仅是不同的尺寸,它们是完全不同的类型.

你需要的是一个动态大小的数组而不是静态大小的数组.即std::vector<uint32_t>::

template <typename T>
class Channel {
    std::vector<T> v;

public:
    Channel(std::initializer_list<T> dims)
    : v(std::accumulate(dims.begin(), dims.end(), size_t{1}, 
                        std::multiplies<size_t>{}))
    { }
};
Run Code Online (Sandbox Code Playgroud)

  • 我会使用`std :: size_t`或类似的积累,而不是`T`. (2认同)