转发可变数量的参数 [英] Forwarding variable number of arguments

查看:101
本文介绍了转发可变数量的参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想像这样模拟示例printf():

Hi, I want to emulate example printf() like this:

void printfLn( const char *format, ... )
{
	printf( format, ... );
	printf( "\n" );
}



有什么方法可以将(...)(其他)参数传递给printf?
我做了些类似于几年前的事情,我不记得怎么做.



Is there any way to pass the (...) (others) argument to printf?
I make some similar to this years ago an I don''t remember how.

推荐答案

是可以的,但是应该使用printf >.请看下面的代码片段:

Yes it is possible, but instead of printf you should use vprintf. Look at the code snippet below:

void printfLn(const char *format, ...)
{
   va_list args;
   va_start(args, format);
   vprintf(format, args);
   printf("\n");
   va_end(args);
}



有关更多详细信息,请参见 vprintf文档 [访问变量参数列表 [



For more details see vprintf documentation[^] and access variable-argument lists[^]


我好几年没看过C ++了.

但是,对我来说,这听起来像是一种立面模式.将格式发送到printfLn中的不同方法,或将它们汇总以合并格式.然后将该结果传递给printf()函数.

Ryan McBeth
I haven''t looked at C++ in years.

But, it sounds like a facade pattern to me. Send the formatting out to different methods within printfLn or aggregate them for combining formats. Then pass that result to the printf() function.

Ryan McBeth


看看 http://en.wikipedia.org/wiki /Stdarg.h [ ^ ].那样应该可以帮助您.
Take a look at http://en.wikipedia.org/wiki/Stdarg.h[^]. That should get you on your way.


这篇关于转发可变数量的参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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