在C ++中将默认值参数放在可变长度函数中的哪里? [英] where to place default value parameter in variable-length function in c++?

查看:39
本文介绍了在C ++中将默认值参数放在可变长度函数中的哪里?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在可变长度参数函数中,"..."必须放在最后.并且启用默认值的参数也必须是最后一个.

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?

现在我有一个日志实用程序:MyPrint(int32_t logLevel,const char * format,...),用于根据'logLevel'打印日志.

Now I have a log utility: void MyPrint(int32_t logLevel, const char *format, ...), which used to print log according to 'logLevel'.

但是,有时我希望它可以用作:MyPrint("Log test number%d",number),不需要'logLevel'.

However, sometimes I hope it can be used as: MyPrint("Log test number%d", number), without 'logLevel' needed.

问题:默认参数和可变参数函数没有帮助.

推荐答案

在您的特定情况下,您可能只想制作两个版本的MyPrint,例如:

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

};

因此您可以像这样调用MyPrint():

So you could call MyPrint() like this:

MyPrint("blah,blah", 123);

或这样:

MyPrint("blah,blah", 123).setLogLevel(5);

这篇关于在C ++中将默认值参数放在可变长度函数中的哪里?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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