Metzen said:
hello,
ok, I want to find the length of an int array that is being passed to a
function:
The following might work. I can't work out whether the standard says it does.
// Begin listing
#include <iostream>
#include <ostream>
#define MACRO(a) (sizeof (a) / sizeof (int))
template <typename T, unsigned N>
int function (T (&) [N]) { return N; }
int test (int a [])
{
// std::cout << function (a) << ", "; // compile-time error
std::cout << MACRO (a) << std::endl; // no error signaled
}
int main ()
{
int array [] = { 1, 2, 3, 4, 5, 6, 7, 8 };
std::cout << function (array) << ", ";
std::cout << MACRO (array) << std::endl;
test (array);
}
// End listing
I get what I expected on mingw32-g++ 3.2 and on bcb32:
the output is "8, 8"; "1". Both compilers report the compile
time error marked if I uncomment that line.
So the template version is slightly superior in that, although
it only works in a small set of situations, it will not compile
unless it can give you the correct answer.
It's probably only rarely that this can be used instead of the
techniques mentioned in the other replies, and even more
rarely that it will provide any significant advantage in speed
or code size. But maybe sometimes.
Yours,
Buster.