Re: templates, arrays and size
Nick Valeontis wrote:
I am confused.
Why does this not work?
Because an array in an argument list really is a pointer. Try:
void foo(int data[]) {
std::cout << sizeof(data)/sizeof(data[0]);
}
---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
template<class T> void PrintArray(T data[], int start, int stop, int
col_length = 3) {
for (int i = start; i <= stop; i++)
std::cout << std::setw(col_length) << data[i] << " ";
std::cout << std::endl;
}
template<class T> void PrintArray(T data[], int col_length = 3) {
//sizeof(data)/sizeof(typeof(data[0]) = 0 !:O
PrintArray(data, 0, sizeof(data)/sizeof(typeof(data[0])), col_length);
}
try:
template <class T, std::size_t N>
void PrintArray(T data[N], int col_length = 3) {
PrintArray(data, 0, N, col_length);
}
---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ---- ----
----
---- ----
If i run the same expression in my main, i get the correct result.. :(
Yes. As you can see, sizeof is a compile time operator, that is the result
is known at compile time. If your function had worked, this would have
required one instance of PrintArray(T[],int) for each size of the array.
????
btw, typeof isn't part of standard C++.
--
rbh