简体   繁体   English

如何使用可变参数模板在 C++ 中获取参数大小的变量编号

[英]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.我需要创建一个函数,它采用变量 no 参数。 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 .它应该打印 empname 的大小:16。 But it print 8 as it is printing size of datatype of template argument.但它打印 8,因为它打印模板参数的数据类型的大小。

Any way out to get size of each argument in parameter pack as i am still learning C++11 variadic template.由于我仍在学习 C++11 可变参数模板,因此有任何方法可以获取参数包中每个参数的大小。

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 * .你得到SIZE:8这是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 :只是在@Hanjoung Lee 的回答中添加另一个示例,您还可以像这样获得数组的大小:

template <typename T, std::size_t Size, typename... Types>
void print(T (&)[Size], Types&... var2)
{
    std::cout << "SIZE:" << Size << std::endl;
    print(var2...);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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