1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
|
#include<iostream>
using namespace std;
// Here is the work function. It takes an array of ANY size.
// You have to explicitly give its size, though.
void print_msg(const char msg_array[], size_t array_size)
{
for (size_t index = 0; array_size > index; ++index)
{
cout << msg_array[index];
}
}
// Here is our compiler magic. It lets us use the above function
// as if it just took an array of any size WITHOUT having to
// explicitly give it. Of course, you could just call the above
// function directly, but this makes so that you don't have to.
//
// If your compiler's optimizer works properly, this function
// should actually disappear from the compiled code.
//
template <size_t N>
inline
void print_msg( const char(& msg_array)[ N ] )
{
print_msg(msg_array, N);
}
int main()
{
const char hello_array[] // no null terminator
= { 'H', 'e', 'l', 'l', 'o', ',', ' ',
'w', 'o', 'r', 'l', 'd', '!', '\n' };
// Now I can use hello_array without caring how long it is.
// All the messy details are handled above.
print_msg(hello_array);
// This would still work also, if SizeOfArray() were still defined above:
//print_msg(hello_array, SizeOfArray(hello_array));
// Likewise:
//print_msg(hello_array, 14);
return 0;
}
|