Finding array length - with a pointer

Started by
11 comments, last by Zahlman 17 years, 7 months ago
Quote:Original post by agi_shi
I decided to cut off the 'numElements' argument because I figured this would also work:

template<class T, size_t N>
size_t size(T[N]) { return N; }


Actually, it should be

template<class T, size_t N>
size_t size(T (&) [N]) { return N; }

Taking the parameter by reference isn't optional: it's what prevents the array from decaying to a pointer.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Advertisement
One possibility if you wish to reduce the number of arguments passed to a function would be to pass a structure as required, instead. For example instead of

void someFunc( HWND* hWnds, int numHWnds );

you could have

typedef struct someFuncArgs
{
HWND* hWnds;
int numHWnds;
} someFuncArgs;

void someFunc( someFuncArgs& args );

... though obviously you wouldn't bother for something with only two arguments. You'll see Windows and other Microsoft code doing this sort of thing very frequently.
OTOH, if taking two arguments isn't a problem, you can give yourself a lot more flexibility at basically no cost, by accepting an iterator range instead:

template <typename HWNDIterator>void SomeMethod(HWNDIterator begin, HWNDIterator end) {  // Of course you could also use std::for_each for this trivial example :)  for (HWNDIterator i = begin; i != end; ++i) {    // By the way, you should not dereference the pointer before subscripting,    // in your original code. Subscripting already implies a dereference;    // foo is equivalent to *(foo + i).    DoSomethingWithWindow(*i);  }}// Passing an array:SomeMethod(array, array + sizeof(array) / sizeof(array[0]));// You might want to use the inline function taking an array reference to// simplify that.// Passing a std::vector, *or any other standard library container*// (except std::(multi)map, because its iterators yield key-value pairs):SomeMethod(container.begin(), container.end());// Passing a single element:SomeMethod(&thing, &thing + 1);

This topic is closed to new replies.

Advertisement