em70
em70

Reputation: 6081

C++11: returning an array

I'm currently facing an interesting situation with STL containers. I have a method that should return different static arrays of objects depending on a parameter. Said objects are of type array<SomeClass, _>.

The reason for the underscore is that they are not all arrays of the same size. Since array is so neatly wrapped and the sizes of the arrays don't change, I was hoping not to be forced into converting the arrays into vectors, for not only is the initialization very neat right now, but I also find array to be the exact structure I want, and a resizable one would be overhead and overkill.

Any chance I can achieve what I want? If not, is there any cleaner solution than using vectors?

Upvotes: 1

Views: 1198

Answers (2)

user1084944
user1084944

Reputation:

You always have the option of writing an array_view<T> class that can act as a reference to array<T,N> for any N.

Upvotes: 0

Edward Loper
Edward Loper

Reputation: 15944

Can the size of the return array be calculated at compile-time based on the arguments? If so, then you can use templates to provide the right value for _. E.g., if the return array is the same length as some argument array, then you could do something like:

template<int N>
array<SomeClass, N> myFunc(array<Foo, N> someArg);

Or if you'll always know the correct size of the return array (at compile time) at the site where you call it, you could do:

template<int N>
array<SomeClass, N> myFunc();

And call it as:

array<SomeClass, 5> = myFunc<5>();

If not, then you'll probably have to use vectors.

Upvotes: 2

Related Questions