468,512 Members | 1,535 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 468,512 developers. It's quick & easy.

a sizeof problem about template

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

Jul 28 '06 #1
2 4495
hu*******@gmail.com wrote:
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.

Jul 28 '06 #2
hu*******@gmail.com 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);
}

--

Frederick Gotham
Jul 28 '06 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

33 posts views Thread by Metzen | last post: by
10 posts views Thread by | last post: by
11 posts views Thread by ajikoe | last post: by
19 posts views Thread by Abubakar | last post: by
90 posts views Thread by pnreddy1976 | last post: by
32 posts views Thread by Abhishek Srivastava | last post: by
11 posts views Thread by nevergone | last post: by
42 posts views Thread by Jess | last post: by
9 posts views Thread by Faisal | last post: by
1 post views Thread by fmendoza | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.