2

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!

2 Answers 2

3

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;
};
Sign up to request clarification or add additional context in comments.

Comments

1

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 );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.