[英]c++11 Creating data member for variable-size std::array in class definition
I'm getting a little confused about std::array and passing it around to different classes. 我对std :: array感到有些困惑,并将其传递给不同的类。 I would like to define a class that accepts a std::array in its constructor, and uses that to set a member variable.
我想定义一个在其构造函数中接受std :: array的类,并使用该类来设置成员变量。 However, since the arrays could be of variable size, I'm not sure how that translates into the class and member variable declarations.
但是,由于数组可能具有可变大小,因此我不确定如何将其转换为类和成员变量声明。 For example:
例如:
// array_param.h
#include <array>
class ArrayParam
{
public:
//constructor?
ArrayParam(std::array<long, ?>& entries);
// member variable?
std::array<long, ?> param_entries;
};
...and... ...和...
// array_param.cpp
#include "array_param.h"
ArrayParam::ArrayParam(std::array<long, ?>& entries)
{
param_entries = entries;
}
The motivation for this is that in my main program I have, for example, two or more very well defined arrays with known fixed sizes. 这样做的动机是,例如,在我的主程序中,我有两个或多个定义良好且已知大小固定的数组。 I would like to perform the same operations on these differently sized arrays, and so such a class to handle these shared operations for arrays of any size is desirable.
我想对这些大小不同的数组执行相同的操作,因此需要一个此类来处理任何大小的数组的这些共享操作。
Any help is greatly appreciated, thank you very much! 非常感谢您的任何帮助,非常感谢!
The size of an std::array
must be known at compile time. 必须在编译时知道
std::array
的大小。 Since you mention your arrays are of known, fixed sizes, you could make the array size a template parameter. 由于您提到数组的大小是已知的固定大小,因此可以将数组大小设为模板参数。
// array_param.h
#include <array>
#include <cstdlib>
template<std::size_t N>
class ArrayParam
{
public:
//constructor?
ArrayParam(std::array<long, N>& entries);
// member variable?
std::array<long, N> param_entries;
};
The length of std::array
is required to be known at compile time. 需要在编译时知道
std::array
的长度。
If not, consider using std::vector
instead. 如果不是,请考虑改用
std::vector
。
From http://www.cplusplus.com/reference/array/array/ 来自http://www.cplusplus.com/reference/array/array/
an array does not keep any data other than the elements it contains (not even its size, which is a template parameter, fixed on compile time ).
数组除了包含的元素外不保留其他任何数据(甚至不包括其大小(它是模板参数, 固定在编译时 ))。
Based on that, the ArrayParam
class may not have much use. 基于此,
ArrayParam
类可能没有太多用处。 I would consider typedef'ing specific kind of arrays, for example 我会考虑例如typedef的特定类型的数组
enum { ArrayLength = 1024 };
typedef std::array< long, ArrayLength > LongArray;
// use and test
LongArray myArray;
assert( myArray.size() == ArrayLength );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.