0

I'm writing logger file. I'd prefer to use macros __FUNCTION__ there. 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)?

3 Answers 3

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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!"); 
}

Comments

2

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

1 Comment

Okay. Thanks for the answer. Will remember this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.