I encountered the following macro definition when reading the globals.h in the Google V8 project.
// The expression ARRAY_SIZE(a) is a compile-time constant of type
// size_t which represents the number of elements of the given
// array. You should only use ARRAY_SIZE on statically allocated
// arrays.
#define ARRAY_SIZE(a) \
((sizeof(a) / sizeof(*(a))) / \
static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
My question is the latter part: static_cast<size_t>(!(sizeof(a) % sizeof(*(a))))). One thing in my mind is the following: Since the latter part will always evaluates to 1, which is of type size_t, the whole expression will be promoted to size_t.
If this assumption is correct, then there comes another question: since the return type of sizeof operator is size_t, why is such a promotion necessary? What's the benefit of defining a macro in this way?
template<class T, size_t N> size_t array_size(T (&)[N]){ return N; }templatefunction is the good choice. There will always be a dependency on compiler optimization. After all,array_size()is a method which will be executed at runtime. May be in C++11, that method can be madeconstexpr; I haven't tested that.constexpr, however you can use another solution if you need to ensure compile-time evaluation: a templated struct holding the result in an enum.sizeof()is the only possible trick in C++03.