开发者

Macros as default param for function argument

I'm writing logger file. I'd prefer to use macros __FUNCTION__ there. I don't 开发者_JAVA技巧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.


You can finally do it without macros magic in 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!"); 
}


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++.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜