a sizeof problem about template

H

hudaiqian

hi,all I encounter a problem with sizeof

template <typename type>
void display(type& a)
{
cout<<sizeof(type)<<":"<<a[0]<<endl;
}

int main()
{
int a[6] = {1,2,3,4,5,6};
display(a);
}

the output is 24:1, its means is sizeof(type) equals 24,but the type
here is int
24 is the sizeof array a,why?Thanks
 
R

Rolf Magnus

hi,all I encounter a problem with sizeof

template <typename type>
void display(type& a)
{
cout<<sizeof(type)<<":"<<a[0]<<endl;
}

int main()
{
int a[6] = {1,2,3,4,5,6};
display(a);
}

the output is 24:1, its means is sizeof(type) equals 24,but the type
here is int

No, it's array[6] of int.
24 is the sizeof array a,why?Thanks

You pass an array to display, which expects a reference to some type. So you
are getting a reference to the array. Within display, 'type' is the type of
that array.
 
F

Frederick Gotham

(e-mail address removed) posted:
hi,all I encounter a problem with sizeof

template <typename type>
void display(type& a)
{
cout<<sizeof(type)<<":"<<a[0]<<endl;
}

int main()
{
int a[6] = {1,2,3,4,5,6};
display(a);
}

the output is 24:1, its means is sizeof(type) equals 24,but the type
here is int
24 is the sizeof array a,why?Thanks


"type" is int[6], not int.

Two remedies:

(1) Use: sizeof *a

or:

(2) Change the template to the following:

#include <cstddef>
#include <iostream>

template<class T,std::size_t len>
void Display(T const (&arr)[len])
{
std::cout << "Size of type: " << sizeof(T)
<< " Quantity: " << len
<< " Total Size: " << sizeof arr << '\n';
}

template<class T>
void Display(T const &obj)
{
Display(reinterpret_cast<T const (&)[1]>(obj));
}

int main()
{
int obj;

int arr[5];

Display(obj);
Display(arr);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,680
Members
48,796
Latest member
Greg L.

Latest Threads

Top