0

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)

  • `sizeof(a)` just returns the size of the pointer. You can not pass an array of unknown size, that information is lost the the call `add`. You would have to `add(a,cnt)` where cnt is 5 for x. – lakeweb Apr 02 '23 at 18:47
  • Or, `template T add(const T(&a)[len]) {` – Ted Lyngmo Apr 02 '23 at 19:05
  • If you use a range based `for`-loop you don't even need to capture the array size: `template auto add(const T& a) { std::remove_extent_t sum{}; for(auto& v : a) sum += v; return sum; }` – Ted Lyngmo Apr 02 '23 at 19:24

0 Answers0