Reputation: 33
I need to create a function which take variable no of argument. The objective of this function will be to get argument and print the data. I have succeeded in implementing this function using variadic template whose code is given below:
void print(T var1, Types... var2)
{
cout << "DATA:"<<var1<< endl ;
print(var2...) ;
}
But now i want to print the size of argument as well . For e.g:
char empname[15+1];
print(empname);
It should print size of empname : 16 . But it print 8 as it is printing size of datatype of template argument.
Any way out to get size of each argument in parameter pack as i am still learning C++11 variadic template.
Upvotes: 2
Views: 229
Reputation: 727
Just to add another example to @Hanjoung Lee's answer, you could also get the size of your array like this :
template <typename T, std::size_t Size, typename... Types>
void print(T (&)[Size], Types&... var2)
{
std::cout << "SIZE:" << Size << std::endl;
print(var2...);
}
Upvotes: 2
Reputation: 2152
I assume that you are trying to do something like:
(Please put up your entire code you tried, next time)
void print() {}
template <typename T, typename... Types>
void print(T var1, Types... var2)
{
cout << "SIZE:"<<sizeof(var1)<< endl ;
print(var2...) ;
}
And when you try run this:
char empname[15+1];
print(empname);
You get SIZE:8
which is the size of char *
. The array is decayed to a pointer when it is passed to a function parameter. This is because of Array-to-pointer decay.
So if you specify the template parameter manually as an array-reference, then it works fine.
char empname[15+1];
print<char (&)[16]>(empname);
However this probably not be what you want. To prevent the decays, you can just change the argument type to reference. Detailed description is here.
template <typename T, typename... Types>
void print(T& var1, Types&... var2)
{
cout << "SIZE:"<<sizeof(var1)<< endl ;
print(var2...) ;
}
Upvotes: 3