[英]std::array of unknown size as a class member
I'm making an N dimensional image format, I want to store the raw data in an 我正在制作N维图像格式,我想将原始数据存储在
std::array<T, multiple of all dimensions>* where T is the type of single channel pixel value
I want the constructor to take an array of channels like {20, 30, 50} to make a 20x30x50 bitmap for example which would make the total length of data 30000. In the end, I want to be able to declare the channel like this 我希望构造函数采用诸如{20,30,50}之类的通道数组来制作20x30x50位图,例如,这将使数据的总长度为30000。最后,我希望能够这样声明通道
auto* channelRed = new Channel<uint32_t>({20, 30, 50});
problem is that std::array expects size to be passed in the template parameters and that would throw a wrench in my N dimensional plan. 问题是std :: array希望在模板参数中传递大小,这会在我的N维计划中造成麻烦。
How can I set up a std::array pointer as a class field in my class so that I could define the length of the array during the constructor execution? 如何在类中将std :: array指针设置为类字段,以便可以在构造函数执行期间定义数组的长度?
PS! PS! yeah, I know I can easily just use a regular array which is what I'm doing right now. 是的,我知道我可以轻松地使用常规数组,这就是我现在正在做的事情。 I'm just trying to figure out what std::array is good for. 我只是想弄清楚std :: array有什么用。
You can't. 你不能 A std::array
must know its size at compile-time. 一个std::array
必须在编译时知道它的大小。 It's part of the type! 这是类型的一部分! A std::array<int, 2>
and a std::array<int, 3>
aren't just different sizes, they're completely different types. 一个std::array<int, 2>
和一个std::array<int, 3>
不仅大小不同,而且是完全不同的类型。
What you need is a dynamically sized array instead of a statically sized one. 您需要的是动态大小的数组,而不是静态大小的数组。 Namely: std::vector<uint32_t>
: 即: 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>{}))
{ }
};
If you know the # of parameters at compile time and want to build your Channel
based on that, it's possible to do that with an array (and a helper function). 如果您在编译时知道#个参数,并希望以此为基础构建Channel
,则可以使用数组(和一个辅助函数)来实现。
You can define your class like so: 您可以这样定义类:
template <typename Array>
class Channel {
Array a;
public:
Channel(Array arr)
: a(arr)
{ }
};
Then have a helper function take care of the type nastyness (based on this make_array ): 然后让一个helper函数处理类型讨厌(基于此make_array ):
template<class T, class... Tail>
auto make_channel(T head, Tail... tail) -> Channel<std::array<T, 1 + sizeof...(Tail)>>
{
return Channel<std::array<T, 1 + sizeof...(Tail)>>({ head, tail ... });
}
Then in your program you can simply do something like: 然后,您可以在程序中简单地执行以下操作:
auto channelRed = make_channel<uint32_t>(20, 30, 50);
And you'll get a Channel
, with an array containing {20, 30, 50}
. 然后您将获得一个Channel
,其中包含一个包含{20, 30, 50}
的数组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.