where to place default value parameter in variable-length function in c++?

本秂侑毒 提交于 2021-02-18 17:59:49

问题


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

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