Not sure why Microsoft went for the templated function + macro approach.

(these snippets ard from the VC++ 2010 Express version of stdlib.h)

Andy

PS UNALIGNED is defined to nothing when compiling for x86. For x64 and Itanium, it ends up as __unaligned, to stop __countof() choking on unaligned data. From MSDN entry of __unaligned

The Itanium processor generates an alignment fault when it accesses misaligned data, and the time to process the fault weakens performance. Use the __unaligned modifier to cause the processor to read data one byte at a time and avoid the fault.

#include<iostream>usingnamespace std;
// Here is the work function. It takes an array of ANY size.// You have to explicitly give its size, though.void print_msg(constchar 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>
inlinevoid print_msg( constchar(& msg_array)[ N ] )
{
print_msg(msg_array, N);
}
int main()
{
constchar 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;
}

Now it works either way.

This trick works because the templated "thunk" function is small and should be inlined, or eliminated from, the actual compiled code.

If you were to instead write just one templated function that actually does all the work, then the compiler will generate a new function for every different array you give it. That would be wasteful (or "code bloat"). [AFAIK there are no optimizers smart enough to recognize this kind of situation.]