Topic: Is Array a type , or a class, or something else?
Author: =?ISO-8859-1?Q?"=D6=DC=CA=E9=D5=DC"?= <horn2005@126.com>
Date: Thu, 16 Apr 2009 17:14:28 CST Raw View
hello,
we can define a array by following code:
int a[8];
then, what is the type of a?
when we use template , can we use array as a class to generate a new
class .
for example:
std::vector<a[] > CArrayVetor or we must do it in other way?
thanks
--
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]
Author: restor <akrzemi1@interia.pl>
Date: Sat, 18 Apr 2009 02:16:44 CST Raw View
> we can define a array by following code:
> int a[8];
> then, what is the type of a?
> when we use template , can we use array as a class to generate a new
> class .
> for example:
> std::vector<a[] > CArrayVetor or we must do it in other way?
The name 'a' in your example has type int[8]; (array of 8 int's).
Therefore, the following code for computing any array's size works:
template< typename T, size_t N >
size_t Size( T(&array)[N] ) // reference to array of N elements
of type T
{
return N;
}
However an array is a special type in many ways. For example it
doesn't have an assignment operator. Therefore the following function
doesn't work:
template< typename T, size_t N >
void assign1( T(&lhs)[N], T(&rhs)[N] )
{
lhs = rhs;
}
Similarly, if you define the following function:
template< typename T >
void assign2( T & lhs, T & rhs )
{
lhs = rhs;
}
It will work for many types, but not for 'a' from your example,
because 'a' is an array and thus doesn't have an assignment operator.
std::vector< int(&)[8] > will not work because int(&)[8] is a
reference and you cannot store references in vector, as reference have
no storage an do not have assignment operator.
std::vector< int[8] > will not work either because arrays (as opposed
to references to arrays) decay to pointers and you will be handling
std::vector< int*> in the end.
If there is a reason you really needed to use a vector of arrays, you
could consider using
std::vector< std::vector<int> >
or
std::vector< boost::array<int> >
or perhaps you need some matrix type.
Regards,
&rzej
--
[ comp.std.c++ is moderated. To submit articles, try just posting with ]
[ your news-reader. If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[ --- Please see the FAQ before posting. --- ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html ]