Type Safety
The COUNTOF macro just described produces correct results when the argument is a genuine array, but it silently produces bad results in other cases. For example, on a typical machine, the output of this code snippet is 1:
int* p = new int[13]; std::cout << COUNTOF(p);
Similar problems occur if the argument is a vector or other array-like class. Even more surprisingly, the following function also outputs 1:
void bad_func(int a[13]) { std::cout << COUNTOF(a); }
The reason for this goes back to the C heritage of C++. Under C rules, even though the formal parameter is declared as int a[13], the compiler implicitly changes the declaration to int* a. Throughout bad_func, a isn't just convertible to a pointer, it actually is a pointer. This change applies only to function parameters, but when it happens, it can be quite unexpected.
Because COUNTOF accepts arguments of types that it does not correctly handle, it clearly is not type safe. Fortunately, the revised COUNTOF in Listing One solves these problems and produces a compile-time error if any improper argument is passed. The new COUNTOF is a drop-in replacement for the old and should work for any correct code that currently uses the old form.
// public interface #define COUNTOF(x) ( \ 0 * sizeof( reinterpret_cast<const ::Bad_arg_to_COUNTOF*>(x) ) + \ 0 * sizeof( ::Bad_arg_to_COUNTOF::check_type((x), &(x)) ) + \ sizeof(x) / sizeof((x)[0]) ) // implementation details class Bad_arg_to_COUNTOF { public: class Is_pointer; // intentionally incomplete type class Is_array {}; template<typename T> static Is_pointer check_type(const T*, const T* const*); static Is_array check_type(const void*, const void*); };