是否有可能有在C可变参数函数没有非可变参数的参数? [英] Is it possible to have a variadic function in C with no non-variadic parameter?

查看:140
本文介绍了是否有可能有在C可变参数函数没有非可变参数的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下功能:

void doStuff(int unusedParameter, ...)
{
    va_list params;
    va_start(params, unusedParameter);
    /* ... */
    va_end(params);
}

作为重构的一部分,我想删除未使用的参数,而不用改变功能的实现。据我所知,这是不可能使用的va_start 当你没有一个最后的非可变参数的参数参考。有没有解决这个办法吗?

As part of a refactor, I'd like to remove the unused parameter without otherwise changing the implementation of the function. As far as I can tell, it's impossible to use va_start when you don't have a last non-variadic parameter to refer to. Is there any way around this?

背景:事实上,这是一个C ++程序,这样我可以利用一些操作符重载神奇的建议<一href=\"http://stackoverflow.com/questions/1436968/variadic-function-without-specified-first-parameter\">here,但我希望不要有更改界面在这一点上。

Background: It is in fact a C++ program, so I could use some operator-overloading magic as suggested here, but I was hoping not to have to change the interface at this point.

现有功能做工作,要求该变量参数列表是空终止,和扫描为NULL,因此它不需要一个领先参数来告诉它有多少争论了。

The existing function does its work by requiring that the variable argument list be null-terminated, and scanning for the NULL, therefore it doesn't need a leading argument to tell it how many arguments it has.

在回应评论:我不的有无的删除未使用的参数,但我会做,如果有一个干净的方式来做到这一点。我希望有会是简单的东西我已经错过了。

In response to comments: I don't have to remove the unused parameter, but I'd do it if there were a clean way to do so. I was hoping there'd be something simple I'd missed.

推荐答案

您的选择是要么离开它,因为它是和使用的va_list ,别名(如果它是GCC)正如其他人所指出的,还是沿着执行exec(2)接口线的东西 - 传递指针的需要数组的 NULL 终止

Your choice is either leave it as it is and use va_list, alias it (if it's GCC) as others pointed out, or do something along the lines of exec(2) interface - passing an array of pointers requiring a NULL terminator:

/* \param args  NULL-terminated array of
 *              pointers to arguments.
 */
void doStuff( void* args[] );

无论哪种方式,这将是更好的重构界面以某种方式把类型系统的优势 - 也许过载上使用精确的参数类型:

Either way it would be much better to refactor the interface to somehow take advantage of the type system - maybe overload on exact argument types used:

void doStuff( int );
void doStuff( const std::string& );
void doStuff( const MyFancyAppClass& );

希望这有助于。

这篇关于是否有可能有在C可变参数函数没有非可变参数的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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