简体   繁体   中英

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. I would like to define a class that accepts a std::array in its constructor, and uses that to set a member variable. 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. 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.

If not, consider using std::vector instead.

From 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. I would consider typedef'ing specific kind of arrays, for example

enum { ArrayLength = 1024 };
typedef std::array< long, ArrayLength >   LongArray;

// use and test
LongArray myArray;
assert( myArray.size() == ArrayLength );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM