问题
in variable-length parameters function, the '...' must be place last. And default value enabled parameters must be last, too.
so, how about both needed in the same one function?
Now I have a log utility: void MyPrint(int32_t logLevel, const char *format, ...), which used to print log according to 'logLevel'.
However, sometimes I hope it can be used as: MyPrint("Log test number%d", number), without 'logLevel' needed.
The question: Default arguments and variadic functions didn't help.
回答1:
In your specific case you might just want make two versions of MyPrint, like:
MyPrint(const char *format, ...)
{
_logLevel = 1;
// stuff
}
MyPrint(int32_t logLevel, const char *format, ...)
{
_logLevel = logLevel;
//stuff
}
On the other hand the Named Parameter Idiom would indeed provide an alternative solution:
class Abc
{
public:
MyPrint(const char *format, ...)
{
_logLevel = 1;
// stuff
}
Abc &setLogLevel(int32_t logLevel)
{
_logLevel = logLevel;
}
// stuff
};
So you could call MyPrint() like this:
MyPrint("blah,blah", 123);
or like this:
MyPrint("blah,blah", 123).setLogLevel(5);
来源:https://stackoverflow.com/questions/16143238/where-to-place-default-value-parameter-in-variable-length-function-in-c