gpt4 book ai didi

c++ - std::array of unknown size 作为类成员

转载 作者:搜寻专家 更新时间:2023-10-31 00:11:54 24 4
gpt4 key购买 nike

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

std::array<T, multiple of all dimensions>* where T is the type of single channel pixel value

我希望构造函数采用像 {20, 30, 50} 这样的 channel 数组来制作 20x30x50 位图,这将使数据的总长度为 30000。最后,我希望能够声明这样的 channel

auto* channelRed = new Channel<uint32_t>({20, 30, 50});

问题是 std::array 期望在模板参数中传递大小,这会给我的 N 维计划带来麻烦。

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

附言!是的,我知道我可以轻松地使用常规数组,这就是我现在正在做的。我只是想弄清楚 std::array 有什么用。

最佳答案

你不能。 std::array必须在编译时知道它的大小。这是类型的一部分! std::array<int, 2>和一个 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>{}))
{ }
};

关于c++ - std::array of unknown size 作为类成员,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32151016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com