Lets start with finding the the number of elements in an array. The conventional C way would be to use sizeof like:
sizeof(array)/sizeof(array)I'm not a big fan of this approach. I have seen production code by seasoned C++ developers that looks like this:
const char* tmp = 0;Of course this is sometimes hidden behind a macro:
int size = sizeof(tmp)/sizeof(tmp);
#define array_size(array) (sizeof(array)/sizeof(array))Either way, this gives the wrong answer. The developer, of course, is not interested in what the size of a pointer to an element divided by the size of an element is.
int size = array_size(tmp);
So, can we do better? Actually, yes, we can.
template <typename T, size_t N>Here we pass an array by reference to array_size() that extracts the size of the array and returns it. I talked briefly about array passing a few years ago.
size_t array_size(const T (&lhs)[N])
We can now use it like so:
int ia;And if we try to use this with a pointer like so:
size_t s = array_size(ia); // s == 10
const char* tmp = 0;We get a compiler error similar to:
size_t s = array_size(tmp); // error
error: no matching function for call to 'array_size(const char*&)'Very nice.
However, sizeof can also be used with a type instead of a variable. In my next post, I'll show how we can create a template that will work with a type instead of a variable.