2

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.

Community
  • 1
  • 1
kim
  • 43
  • 4
  • 1
    possible duplicate of [Default arguments and variadic functions](http://stackoverflow.com/questions/4130613/default-arguments-and-variadic-functions) – TemplateRex Apr 22 '13 at 09:16
  • Curious as to why you need to have variable-length parameter lists and default values... You should be able to come up with a solution that uses one or the other. – krsteeve Apr 22 '13 at 17:31
  • 1
    The specific solution for what you want to do with `MyPrint()` would be to have two overloads. – Michael Burr May 02 '13 at 06:46
  • What have you tried so far, and what were the results? Code please. And compiler output. – TobiMcNamobi May 02 '13 at 08:19

1 Answers1

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);
TobiMcNamobi
  • 4,687
  • 3
  • 33
  • 52