2

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.

HolyBlackCat
  • 78,603
  • 9
  • 131
  • 207
macmore
  • 33
  • 5

2 Answers2

3

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...) ;
}
Hanjoung Lee
  • 2,123
  • 1
  • 12
  • 20
  • Thanks !!! This is what i needed. Your answer taught me new concept called as "decay". Query is solved now. – macmore Jan 06 '20 at 10:19
2

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...);
}
Storm
  • 717
  • 6
  • 11
  • But is this solution applicable for different datatype like long,int,double as well. – macmore Jan 06 '20 at 11:41
  • @macmore Yes, if you mean size of the array and not size in bytes, since the value of `Size` would basically be the result of `sizeof(var1) / sizeof(var1[0])` – Storm Jan 06 '20 at 12:53