Re: Determining array size
From: John Harrison (john_andronicus_at_hotmail.com)
Date: 06/21/04
- Next message: Joseph Lanctot: "class X containing an stl list<X> in MS Visual C++"
- Previous message: Alf P. Steinbach: "Re: Determining array size"
- In reply to: David Rubin: "Re: Determining array size"
- Next in thread: Thomas Matthews: "Re: How to know the buffer size and increase buffer size in c++"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Mon, 21 Jun 2004 19:21:33 +0100
"David Rubin" <davidrubin@warpmail.net> wrote in message
news:82b37be.0406211008.2218a3d1@posting.google.com...
> "John Harrison" <john_andronicus@hotmail.com> wrote in message
>
> [snip]
> > template<typename T, size_t N>
> > size_t array_size(T (&dummy)[N]) { return N; }
> >
> > dummy is a reference to an array T of size N. Because the parameter is
> > unused C++ allows you to omit it as AngleWyrm did.
>
> Of course, this generates a function for every different type T and
> size N. It's more efficient to use
>
> #define array_size(X) (sizeof X / sizeof *X)
>
> which has the same semantics. You only lose some type-safety, but this
> typically not a problem.
>
> /david
Not necessarily, if you make the template version an inline function.
Your version suffers from the big problem that is will compile for pointers.
Its quite common for an array to change to a pointer, for instance when some
code is refactored into a different function but the array stays in the
original function and is passed to the new function as a pointer. In that
case your version will compile but give meaningless results. The template
version will give a compile error.
john
- Next message: Joseph Lanctot: "class X containing an stl list<X> in MS Visual C++"
- Previous message: Alf P. Steinbach: "Re: Determining array size"
- In reply to: David Rubin: "Re: Determining array size"
- Next in thread: Thomas Matthews: "Re: How to know the buffer size and increase buffer size in c++"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|