C++ working with memory, templates

Question:

#include <iostream>

using namespace std;

template <typename type>
int size(type a) {
    return sizeof(a);
}

int main() {
    int a[10] = {5};
    cout << size(a) << " " << sizeof(a) << endl; 
    return 0;
}

Hello! Can you please explain why size(a) returns 8 but sizeof(a) ) returns 40 ? And how to get information about the memory used by the array inside the function template? Thanks!

Answer:

In this case, the a in the template will not be an array, because arrays cannot be passed by value, and array arguments are implicitly converted to pointer arguments. This can be easily verified by adding a test to the method:

static_assert(::std::is_same_v<int *, type>);

To correctly determine the size of the original object, you will have to pass it by reference:

template <typename type>
::std::size_t size(type const & a) {
    return sizeof(a);
}
Scroll to Top