在 C++ 中处理 va_args [英] Process va_args in c++
本文介绍了在 C++ 中处理 va_args的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个函数 A(...)
和 B(...)
.现在我必须在 A
中调用 B
,任何将 ...
从 A
传递到 的方法>B
?伪代码:
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. 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
这样的函数存在的原因.)
(This is also why functions like vprintf
exists.)
如果您使用的是 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)...);
}
这篇关于在 C++ 中处理 va_args的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文