/* * C++ 11 introduced the array template, which can create arrays which have * much saner behavior, and without loss of run-time efficiency. */ #include #include 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 &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 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()); }