Re: Can I get some code executed while pre-compile?
Giovanni Dicanio <giovanni.dicanio@invalid.it> wrote:
For example, there was a discussion also about the countof()
template, I stop at countof made using the preprocess, i.e.
#define countof( a ) ( sizeof(a) / ( sizeof( (a)[0] ) )
but there is some template metaprogramming "magic" that allows to
write a countof which gives a compiler error if you pass a pointer to
it (instead of array).
Something like this, I guess:
template <typename T, size_t N>
char (& countof_helper(T (&)[N]) )[N];
#define countof(a) sizeof(countof_helper(a))
countof_helper is a function taking a reference to an array of any type
and any size, and returning a reference to an array of char of the same
size. The function doesn't need to be implemented, just declared. sizeof
only cares about the type of the expression, but doesn't actually
evaluate the expression.
Passing anything other than an array to countof_helper would fail
template parameter deduction, and you would get a compiler error.
--
With best wishes,
Igor Tandetnik
With sufficient thrust, pigs fly just fine. However, this is not
necessarily a good idea. It is hard to be sure where they are going to
land, and it could be dangerous sitting under them as they fly
overhead. -- RFC 1925