| #include <iostream> |
| unsigned int const LIST_SIZE = 1000; |
| |
| template<class A, const unsigned int S> |
| struct SIZED_ARRAY |
| { |
| // array object |
| A array[S]; |
| }; |
| |
| // to make the main() code prettier |
| typedef SIZED_ARRAY<int, LIST_SIZE> INT_ARRAY; |
| |
| // map a function (argument 1) to an array (argument 2) |
| template<class R, class A, const unsigned int S> |
| SIZED_ARRAY<R, S> map(R (*func)(A), SIZED_ARRAY<A, S> arr) |
| { |
| // create return array |
| SIZED_ARRAY<R, S> ret_arr; unsigned int i = S; |
| while (i--) ret_arr.array[i] = func(arr.array[i]); |
| |
| // return the array |
| return ret_arr; |
| } |
| |
| // our test function |
| int multiply_two(int n) |
| { return n << 1; }; |
| |
| int main() |
| { |
| int i; INT_ARRAY listA; |
| |
| // fill up the array with values |
| for (i = 0; i < LIST_SIZE; ++i) |
| listA.array[i] = i; |
| |
| // GCC can infer function template parameters from arguments |
| INT_ARRAY listB = map(multiply_two, listA); |
| |
| // print the results |
| for (i = 0; i < LIST_SIZE; ++i) |
| std::cout << listA.array[i] << '\t' << listB.array[i] << std::endl; |
| |
| return 0; |
| }; |