简体   繁体   English

宏作为函数参数的默认参数

[英]Macros as default param for function argument

I'm writing logger file.我正在写记录器文件。 I'd prefer to use macros __FUNCTION__ there.我更喜欢在那里使用宏__FUNCTION__ I don't like the way like:我不喜欢这样的方式:

Logger.write("Message", __FUNCTION__);

Maybe, it's possible to make something like:也许,有可能做这样的事情:

void write(const string &message, string functionName = __FUNCTION__)
{
   // ...
}

If not, are there any ways to do that stuff not by hands (I mean passing function name)?如果没有,有没有什么方法可以不用手来做这些事情(我的意思是传递函数名)?

You could do something like that by wrapping it all in a macro:您可以通过将其全部包装在一个宏中来做类似的事情:

#define log(msg) Logger.write(msg, __FUNCTION__)

The downside is that you will need to have Logger in scope when using this macro.缺点是在使用此宏时,您需要在范围内使用Logger

Macros work just by text substitution - the preprocessor puts the macro definition in place of its name.宏仅通过文本替换工作 - 预处理器将宏定义放在其名称的位置。 You can't have "intelligent" macros like the one you suggest.您不能拥有像您建议的那样的“智能”宏。

There is no support for what you want in standard C++.标准 C++ 不支持您想要的内容。

You can finally do it without macros magic in c++20:你终于可以在 c++20 中不用宏魔法来做到这一点:

void write(std::string_view message, const std::source_location& location =
                                         std::source_location::current()) {
  std::cout << "Message= " << message
            << ", Function=" << location.function_name();
}

int main() { 
  write("Hello world!"); 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM