所以我有两个函数都有相似的参数
void example(int a, int b, ...);
void exampleB(int b, ...);
现在,example
调用exampleB
,但我如何在不修改exampleB
的情况下传递变量参数列表中的变量(因为这在其他地方也已经使用了)。
你不能直接做;您必须创建一个使用va_list
的函数:
#include <stdarg.h>
static void exampleV(int b, va_list args);
void exampleA(int a, int b, ...) // Renamed for consistency
{
va_list args;
do_something(a); // Use argument a somehow
va_start(args, b);
exampleV(b, args);
va_end(args);
}
void exampleB(int b, ...)
{
va_list args;
va_start(args, b);
exampleV(b, args);
va_end(args);
}
static void exampleV(int b, va_list args)
{
...whatever you planned to have exampleB do...
...except it calls neither va_start nor va_end...
}
也许在池塘里扔块石头,但在C++11变量模板中似乎可以很好地工作:
#include <stdio.h>
template<typename... Args> void test(const char * f, Args... args) {
printf(f, args...);
}
int main()
{
int a = 2;
test("%s\n", "test");
test("%s %d %d %p\n", "second test", 2, a, &a);
}
至少,它可以使用g++
。