Hello I got a problem while studying C++ template. Here is the code I'm curious about
#include <iostream>
using namespace std;
template<class T>
T add(T a[]) {
int len = sizeof(a) / sizeof(T);
T sum = 0;
for (int i = 0;i < len; i++)
{
sum += a[i];
}
return sum;
}
int main() {
int x[] = { 1,2,3,4,5};
double d[] = { 1.2, 2.3, 4.5, 4.5, 5.6, 6.7 };
cout << "sum of x[] = " << add(x) << endl; // 15
cout << "sum of d[] = " << add(d) << endl; // 23.7
}
The problem is that the results are different.
add(x) result is 3 (must be 15)
add(d) result is 1.2 (must be 23.7)
so I fix add function like this
T add(T a[])
{
int len = sizeof(a) / sizeof(a[0]);
T sum = 0;
for (int i = 0;i < len; i++)
{
sum += a[i];
}
return sum;
}
still the results are not change correctly
so I check something
T add(T a[])
{
int len = sizeof(a) / sizeof(T);
cout << "sizeof(a) = " << sizeof(a) << endl << "sizeof(a[0]) = " << sizeof(a[0]) << endl << "sizeof(T) = " << sizeof(T) << endl;
T sum = 0;
for (int i = 0;i < len; i++)
{
sum += a[i];
}
return sum;
}
I verified that the result value of sizeof(a[0]) and sizeof(T) works well but the sizeof(a) value is 8(must be 20, 48)
How can I get the correct result?(While using template)