使用Variadic模板打开参数列表 [英] Unpacking Argument List with Variadic Template

查看:169
本文介绍了使用Variadic模板打开参数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在使用不透明数据类型的旧C-API周围创建一个C ++便利包装。有一个特定的C函数采用格式字符串,以及使用C < stdarg.h> 设施的可变数量的参数。作为我的包装器的一部分,我想能够传递任意数量的参数(包括C ++对象)到这个函数。然而,由于显然< stdarg.h> 设施不能使用非POD数据,我创建了一个模板转换函数,它转换C ++对象(如 std :: string )转换为POD等效项。

I'm trying to create a C++ convenience wrapper around an old C-API that uses an opaque data type. There's one particular C-function which takes a format string, along with a variable number of arguments using the C <stdarg.h> facilities. As part of my wrapper, I want to be able to pass an arbitrary number of arguments (including C++ objects) to this function. However, since obviously the <stdarg.h> facilities can't work with non-POD data, I created a templated conversion function which converts C++ objects (like std::string) into POD equivalents.

我认为这整个事情将是一个简单的练习使用C ++ 0x variadic模板,但我很难弄清楚如何编写这个函数,以适当的方式展开参数包,同时应用我的转换函数到每个参数。

I thought this whole thing would be an easy exercise using C++0x variadic templates, but I'm having difficulty figuring out how to write this function in a way that properly unrolls the argument pack while applying my conversion function to each argument.

到目前为止:

   template <class T, class... Args>
   void apply(OPAQUE* object, const char* fmt_string, T&& val, Args&&... args)
   {
      apply(object, fmt_string, Convert(val), args...);
   }

   template <class... Args>
   void apply(OPAQUE* object, const char* fmt_string, Args&&... args)
   {
      C_API_Function_Call(object, fmt_string, args...);
   }

当然,这不工作,因为递归函数调用从来没有真正解包 Args ... ,所以它只是递归,直到堆栈溢出。我不知道如何解开参数,同时将当前参数传递给 Convert 函数,然后递归传递

Of course, this doesn't work because the recursive function call never actually unpacks the Args..., so it just recurses until the stack overflows. I can't figure out how to make it unpack the arguments while also passing the current argument to the Convert function, and then recursively passing along the result.

这是否有办法呢?

推荐答案

认为您需要与完成转发时相同的语法:

I think you need the same syntax as when you do perfect forwarding :

template <class... Args>
void apply(OPAQUE* object, const char* fmt_string, Args&&... args)
{
   C_API_Function_Call(object, fmt_string, Convert(std::forward<Arg>(args))...);
}

省略号...可以放在包含参数包,而不仅仅是在参数包本身的右边。

The ellipsis ... can be placed at the right of an expression containing the argument pack, and not only directly at the right of the argument pack itself.

因此,

func(args ...)expand to func(arg1,arg2,arg3,[...],argN)

func(args)...展开为func(arg1),func(arg2),[...],func(argN)

So, :
func(args...) expand to func(arg1, arg2, arg3, [...] , argN)
func(args)... expand to func(arg1), func(arg2), [...] , func(argN)

这篇关于使用Variadic模板打开参数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆