c++ - 可变参数函数,将值传递给另一个函数

标签 c++ c

<分区>

我有一个带有一些可变参数 params 的函数,我需要在其中调用另一个传递此参数的函数。 比如有人调用这个函数:

bool A(const char* format, ...)
{
  //some work here...
  bool res = B(format, /*other params*/);
  return res;
}

bool B(const char* format, /**/, ...)
{
   va_list arg;
   va_start(arg, format);
   //other work here...
}

我需要知道,如何通过 A 到 B 函数接收的椭圆传递变量参数。谢谢

最佳答案

您不能直接这样做,因此您需要遵循 C 库使用 fprintf/vfprintf 函数组所遵循的相同模式。

这个想法是将实现放在v前缀的函数中,并使用没有v前缀的面向用户的函数来“展开” va_list 在调用真正的实现之前。

bool A(const char* format, ...)
{
  //some work here...
   va_list arg;
   va_start(arg, format);
   bool res = vB(format, arg);
   va_end(arg);
   return res;
}

bool B(const char* format, /**/, ...)
{
   va_list arg;
   va_start(arg, format);
   bool res = vB(format, arg);
   va_end(arg);
   return res;
}

bool vB(const char* format, va_list arg) {
    // real work here...
}

关于c++ - 可变参数函数,将值传递给另一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23371150/

相关文章:

c++ - 使用没有模板参数的模板类

c++ - 添加多个字符串值

c - SDL2 窗口大小比应有的大

c - Valgrind 和释放特殊指针数组

c++ - 将 FILE * 转换为 CMemFile(或从 FILE * 检索 void*)

c++ - 在没有参数列表的情况下无效使用模板名称 'x'

c - 使用 write 函数将 double 写入标准输出

C中十进制转二进制

c - 提取字符串中的一系列数据

C++11:重载无法解析递归 decltype