流程va_args在C ++ [英] Process va_args in c++

查看:118
本文介绍了流程va_args在C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数 A(...) B(...)。现在,我要叫 B A ,任何方法来传递 ... A B ?伪code:

I have a function A(...) and B(...). Now I have to call B inside A, any methods to pass that ... from A into B? Pseudocode:

void A(...)
{
   // Some operators
   B(...); // Instead of ... I need to pass A's args
}

P.S。我知道这可能使用宏但什么函数来完成。

p.s. I know this could be done using macros but what about functions.

推荐答案

您不能转发va_args。您只能转发va_list的。

You can't forward va_args. You can only forward va_list.

void vB(int first, va_list ap)
{
   // do stuff with ap.
}

void B(int first, ...)
{
   va_list ap;
   va_start(ap, first);
   vB(first, ap);
   va_end(ap);
}

void A(int something_else, int first, ...)
{
   va_list ap;
   va_start(ap, first);
   vB(first, ap);       // <-- call vB instead of B.
   va_end(ap);
}

(这也是为什么像 vprintf 函数存在。)

如果您使用的是C ++ 11,你可以用完美转发可变参数模板做到这一点:

If you are using C++11, you could do this with variadic templates with perfect forwarding:

template <typename... T>
void A(T&&... args)
{
    B(std::forward<T>(args)...);
}

这篇关于流程va_args在C ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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