A
amparikh
Hi all,
I was just browsing the archives when I saw one fo the messages posted
recently about array size template et al.
All along, I have been using the usual template to get the size of the
array.
template<typename T, std::size_t N>
std::size_t size_of(T(&)[N])
{
return N;
}
But as one person pointed out, the following definition fails with the
above template, which is what I have always noticed when I use similar
definitions.
int x[5];
int y[size_of(x)]; //fails here
I always went back to the simple way in these definition
int y[sizeof(x)/sizeof(*x)]; //the simple way.
The person who pointed out the error, also had the template that
works.I would like to use this template all the time, but I am not
quite sure, what it is exactly doing. It is trying to get a reference
to an array and then get the size of that array(which itself is a
reference to a char)..Not quite sure. Can somebody explain ?
template <typename T, unsigned N>
char ( & NelemArrayFunc( T ( & )[ N ] ) )[ N ];
#define Nelem( A ) (sizeof( NelemArrayFunc( A ) ))
Thanks.
I was just browsing the archives when I saw one fo the messages posted
recently about array size template et al.
All along, I have been using the usual template to get the size of the
array.
template<typename T, std::size_t N>
std::size_t size_of(T(&)[N])
{
return N;
}
But as one person pointed out, the following definition fails with the
above template, which is what I have always noticed when I use similar
definitions.
int x[5];
int y[size_of(x)]; //fails here
I always went back to the simple way in these definition
int y[sizeof(x)/sizeof(*x)]; //the simple way.
The person who pointed out the error, also had the template that
works.I would like to use this template all the time, but I am not
quite sure, what it is exactly doing. It is trying to get a reference
to an array and then get the size of that array(which itself is a
reference to a char)..Not quite sure. Can somebody explain ?
template <typename T, unsigned N>
char ( & NelemArrayFunc( T ( & )[ N ] ) )[ N ];
#define Nelem( A ) (sizeof( NelemArrayFunc( A ) ))
Thanks.