Comparing the usual methods of passing native and template arrays.
/*
* C++ 11 introduced the array template, which can create arrays which have
* much saner behavior, and without loss of run-time efficiency.
*/
#include <iostream>
#include <array>
using namespace std;
// Native language array passing. Common to pass the size as a second
// parameter, since the array can't tell you.
void rcv(int arr[], int size)
{
cout << "Language plain: sizeof(arr) = "
<< sizeof(arr) << " (storage space for a pointer)" << std::endl
<< " size = " << size
<< " (from extra parameter)" << endl;
// Print the array using a subscript.
cout << " ";
for(int m = 0; m < size; m++)
cout << arr[m] << " ";
cout << endl;
}
// Passing a template array. It should generally be passed as a reference,
// unless you want to copy the entire array whenever you pass it. Also
// note that the size must be repeated in the parameter declaration.
void rcv(array<int, 9> &arr)
{
cout << "Template: sizeof(arr) = "
<< sizeof(arr) << " (storage space for whole array)" << std::endl
<< " size = " << arr.size()
<< " (from array itself)" << endl;
// Print the array using a subscript.
cout << " ";
for(int m = 0; m < arr.size(); m++)
cout << arr[m] << " ";
cout << endl;
}
int main()
{
// Normal language array.
const int SIZE = 9;
int arrlang[SIZE] = { 10, 11, 12, 13, 14, 15, 16, 17, 18 };
// Template array.
array<int, SIZE> arrtempl = { -10, -11, -12, -13, -14, -15,
-16, -17, -18 };
// Once declared, they're pretty much the same. Except that the
// template array knows how big it is.
cout << "In main, physical size of each object: "
<< (sizeof arrlang) << " " << (sizeof arrtempl) << endl << " ";
for(int i = 0; i < SIZE; ++i)
cout << arrlang[i] << " ";
cout << endl << " ";
for(int i = 0; i < arrtempl.size(); ++i)
cout << arrtempl[i] << " ";
cout << endl;
// Now run the functions.
rcv(arrlang, SIZE);
rcv(arrtempl);
// Or you could do this. Perhaps to use a new-style array with a
// function you wrote earlier, or as a way to accept an array of
// any size.
rcv(arrtempl.data(), arrtempl.size());
}
Starting with the 2011 standard, C++ adds the array header, which
provides an alternative way to create arrays with additional features.
In particular, the new-style template array
- Has the same run-time efficiency and implementation as the
built-in array.
- Can be subscripted just like a built-in array.
- Pass like regular C++ objects, and are not subject to the
specialized passing rules for arrays. Usually, you want to pass them
by reference, as done here, to avoid copying them.
- The size of the array sent must match the size in the declared
parameter.
- Has a size() method so you can ask how big it is.