Re: SOLUTION: compile time array size using type only
John Moeller wrote:
kanze wrote:
template< typename N, size_t N >
char (&array_size( T (&array)[ N ] ))[ N ] ;
which allows writing things like:
double someArray[] = { 0.1, 0.2, 0.5, 1.0 } ;
int length = sizeof( array_size( someArray ) ) ;
...
As an aside, I'm curious; could you not just have easily written:
template< typename T, size_t N >
size_t array_size( T (& array)[ N ] ) { return N; }
so that you could have written:
double someArray[] = { 0.1, 0.2, 0.5, 1.0 } ;
int length = array_size( someArray ) ;
thus directly obtaining the array size, rather than using sizeof?
In this case, yes, and in fact, that is the way it is done in my
own library. The solution above came about as a result of a
discussion in de.comp.lang.iso_c++, where it was also desired to
be able to do something like:
double secondArray[ sizeof( array_size( firstArray ) ) ] ;
That's what I meant when I said: "Obviously, the problem is even
easier if you don't require a constant integral expression."
(Unless I'm using static initialization, or the initialization
list is being used to determine the size, my arrays are always
std::vector. Which means that I don't need a constant integral
expression. So my code uses the simple forms:
template< typename T, size_t N >
size_t
size( T (&array)[ N ] )
{
return N ;
}
and the equivalent for begin() and end(). The names of the
functions being chosen, of course, to correspond to those of the
member functions in an STL container.)
--
James Kanze GABI Software
Conseils en informatique orient?e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S?mard, 78210 St.-Cyr-l'?cole, France, +33 (0)1 30 23 00 34
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]