How do you declare a pointer to a C++11 std::array?

whitebloodcell picture whitebloodcell · Apr 9, 2014 · Viewed 16.8k times · Source

Depending on a variable, I need to select the SeedPositions32 or SeedPositions16 array for further use. I thought a pointer would allow this but I can't seed to make it work. How do you declare a pointer to a C++11 std::array? I tried the below.

array<int>* ArrayPointer;
//array<typedef T, size_t Size>* ArrayPointer;
array<int,32> SeedPositions32 = {0,127,95,32,64,96,31,63,16,112,79,48,15,111,80,
                               47,41,72,8,119,23,104,55,87,71,39,24,7,56,88,103,120};
array<int,16> SeedPositions16 = {...}

Answer

juanchopanza picture juanchopanza · Apr 9, 2014

std::array has a template parameter for size. Two std::array template instantiations with different sizes are different types. So you cannot have a pointer that can point to arrays of different sizes (barring void* trickery, which opens its own can of worms.)

You could use templates for the client code, or use std::vector<int> instead.

For example:

template <std::size_t N>
void do_stuff_with_array(std::array<int, N> the_array)
{
  // do stuff with the_array.
}

do_stuff_with_array(SeedPositions32);
do_stuff_with_array(SeedPositions16);

Note that you can also get a pointer to the data:

int* ArrayPtr =  SeedPositions32.data();

but here, you have lose the size information. You will have to keep track of it independently.