Re: A type-safe, compile-time constant for the array size
Seungbeom Kim schrieb:
I've never seen such a technique elsewhere before, and feel it's quite
clever and useful. What do others think?
His claims and implementation are quoted below:
* Readable notation.
* Produces a compile-time constant.
* Works even for local types.
* Works on older compilers (Visual C++ 6, for instance).
// 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*);
};
I would like to add a final remark (hoping that
it will be read, because this thread seemed to
have died):
I think that the assertion of author of the
above static array size deducer concerning
validity for local types is not per se true.
AFAIK, the tricky point seems to be in which
way a failure of the template overload of
check_type is provoked, e.g. either during overload
resolution (where an error would occur!) or during
type deduction (SFINAE), where it should fail
silently, because local type errors are not
explicitely mentioned in 14.8.2. The complete story
is explained and resolved (to the working version)
in the - now ready - issue
http://www2.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#488
Greetings from Bremen,
Daniel Kr|gler
--
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]