【发布时间】:2018-01-24 16:00:32
【问题描述】:
在 C++ 中,我们可能会这样写:
#include <cassert.h>
#include <cstdio.h>
#include <cstdarg.h>
void func(..., short end = 0) {
// prevent caller from overriding default value with something other than null
assert(end == 0);
va_list args;
short x;
x = va_arg(args, short);
while (x != 0) {
printf("%d", va_arg(args, short));
}
va_end(list);
return;
}
但是,C 不支持默认函数参数。有什么办法可以强制func 在其参数列表的末尾有一个尾随空字符?有没有办法让程序员不显式地将终止的 null 传递给函数?
我们不希望看到如下调用:
int x = 5;
float y = 6.4;
func(x, y, 0);
我们只想要func(x, y);。
是否可以编写一个可以转换文本的宏
func(x, y);
进入通话:
func(x, y, 0);?
有没有什么方法可以在没有宏的情况下做到这一点?
【问题讨论】:
-
如果你想将函数参数固定为某个常数值,那么它可能一开始就不应该是参数。
-
简答 -> 你不能。长答案->你仍然不能。
-
嗯,这也不是有效的 C++。
标签: c function variadic-functions default-arguments