variadic function - how to ensure parameters passed correctly

社会主义新天地 提交于 2019-12-23 19:35:12

问题


Is there any way (built-in or a code pattern) to ensure that a variadic function is passed the correct number of parameters? (This will be included as part of an API obviously, I can check my own internal code.)

I was considering requiring a UN32 Magic Number to be the last argument passed and check that for validity in the variadic function. Does anyone have any thoughts on that?


回答1:


You could use the PP_NARG macro to add a count semi-automatically.

int myfunc (int count, ...);
#define MYFUNC(...) myfunc(PP_NARG(__VA_ARGS__), __VA_ARGS__)

MYFUNC(a,b,c,d);
MYFUNC(a,b,c,d,e,f,g);

gcc -E produces:

int myfunc (int count, ...);

myfunc(4, a,b,c,d);
myfunc(7, a,b,c,d,e,f,g);



回答2:


va_* macros just pop the variables from the local stack, so you have to trust the user. passing an array/size tuple could be safer, I think.




回答3:


There is no definitive way in C or C++ to ensure that the correct number of arguments have been passed to a variadic function. Even requiring a signature is not guaranteed to work as it may clash with the value of a valid argument. You will probably be much better off passing a vector<> as the element count retrieved is accurate.




回答4:


Couldn't you use the variadic template feature of C++0x applied to a function? This would generate a vararg function that is type-safe .

See this link with it's type-safe printf implementation using a variadic templated function

http://www2.research.att.com/~bs/C++0xFAQ.html#variadic-templates




回答5:


It depends on what you mean by "ensure that a variadic function is passed the correct number of parameters"...

Passing a UN32 Magic Number as last argument will allow you to determine where the list of arguments ends, so their overall number. So, by counting how many arguments you have found before UN32, you know how many arguments you have and your function should know whether is it enough. Don't know if it is ok for you to determine this at run-time (it could be too late)...

Anyway, usually variadic functions have a fixed argument list portion representing the mandatory arguments (at least one); so possibly this should be the way for you to ensure that the function gets the correct number of arguments...




回答6:


No. Not possible.

Variadic breaks type-safety in a way that cannot be fixed.

If you want type-safety back, then consider breaking variadic function into several typesafe member function of a [small] class that holds the shared state between their calls.

This is always possible, even if multiple calls might look awkward compared to single variadic call.

Shared state is probably why you wanted variadic function in the first place.

Take iostream vs printf as example.



来源:https://stackoverflow.com/questions/6821900/variadic-function-how-to-ensure-parameters-passed-correctly

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!