On Jun 28, 9:52 pm, Kai-Uwe Bux <jkherci...@gmx.netwrote:
aaragon wrote:
I was wondering if there is a way to determine the size of
an array at runtime. Let's say I have a class that has one
of its constructors taking an array:
template <class T>
class A {
// constructors
...
A(const T array[]) {
// use array
}
// other fns...
};
So of course I cannot use the sizeof operator because the
array can be created at runtime, so
sizeof(array)/sizeof(array[0]) won't work. Now, operator
delete[] can still figure the size of an array, right?
[...]
Therefore, there has to be a way to determine the size of it.
[...]
(b) If you need that information, the easiest way is to use
std::vector. If you really want to use arrays, the only way to
get the length is to not forget it: when you new[] the array,
you know the length; just don't throw away that piece of
information.
If the arrays are dynamically allocated (as his mention of
delete[] suggests), then he definitely should be using
std::vector. If they're not, of course, something like:
template< typename T >
class A
{
template< size_t N >
Array( T const (&array)[ N ] ) ...
} ;
can also be used.
(More generally, if he wants to support both, it should probably
be:
template< typename ForwardIterator >
Array( ForwardIterator begin, ForwardIterator end ) ;
He can then use the de facto standard begin and end:
template< typename T, size_t N >
T*
begin( T (&array)[ N ] )
{
return array ;
}
template< typename T, size_t N >
T*
end( T (&array)[ N ] )
{
return array + N ;
}
to invoke this constructor with a C style array.)
--
James Kanze (GABI Software) email:ja*********@gmail.com
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