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[0])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[0]);
#define array_size(array) (sizeof(array)/sizeof(array[0]))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.
inline
size_t array_size(const T (&lhs)[N])
{
return N;
}
We can now use it like so:
int ia[10];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.
2 comments:
Oh, that is wicked cool.... Gotta love templating
The coderwall explains in Some detail the theory of how best to get the size of an array in C++ https://coderwall.com/p/nb9ngq/better-getting-array-size-in-c
Post a Comment