简体   繁体   中英

How to get variable no of argument with its size in C++ using variadic template

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 eg:

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.

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...) ;
}

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...);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM