Replace Macro with modern C++

Viewed 247

I have the following macro

 #define Error(error_msg) ErrorMsg(__FILE__,__LINE__,error_msg)

I was wondering whether this could be replaced with more modern c++ which can be defined once and for all in a header file?

My function ErrorMsg has following interface

void ErrorMsg(const std::string &file, int line, const std::string &report)
1 Answers

Like @m88 said in the comments, std::source_location is the modern C++ way to get the filename, function name and line number - so modern, in fact, that it is only supported for really new compilers that support C++20.

Here is a program that does both the macro way and the std::source_location way so that you can compare them:

#include <iostream>
#include <source_location>

void ErrorMsg(const std::string &file, int line, const std::string &message)
{
    std::cout << "info: " << file << ":" << line << ": " << message << "\n";
}

#define ErrorMacro(error_msg) ErrorMsg(__FILE__,__LINE__,error_msg)

void ErrorFunction(const std::string &message, const std::source_location& location = std::source_location::current())
{
    std::cout << "info: "
    << location.file_name() << "("
    << location.line() << ":"
    << location.column() << ") `"
    << location.function_name() << "` "
    << message << '\n';
}

int main()
{
    ErrorMacro("Hello World");    ErrorFunction("Hello World");

    return 0;
}

It produces:

info: ./example.cpp:23: Hello World
info: ./example.cpp(23:62) `int main()` Hello World

Try it at https://godbolt.org/z/xdh4Y6

And here's one where the macro version can print the function name as well:

#include <iostream>
#include <source_location>

void ErrorMsg(const std::string &file, const std::string &function, int line, const std::string &message)
{
    std::cout << "info: " << file << "(" << line << ") `" << function << "` " << message << "\n";
}

#ifdef _MSC_VER
#define ErrorMacro(error_msg) ErrorMsg(__FILE__,__FUNCSIG__,__LINE__,error_msg)
#else
#define ErrorMacro(error_msg) ErrorMsg(__FILE__,__PRETTY_FUNCTION__,__LINE__,error_msg)
#endif

void ErrorFunction(const std::string &message, const std::source_location& location = std::source_location::current())
{
    std::cout << "info: "
    << location.file_name() << "("
    << location.line() << ":"
    << location.column() << ") `"
    << location.function_name() << "` "
    << message << '\n';
}

int main()
{
    ErrorMacro("Hello World");    ErrorFunction("Hello World");

    return 0;
}

It produces:

info: ./example.cpp(27) `int main()` Hello World
info: ./example.cpp(27:62) `int main()` Hello World

Try it at https://godbolt.org/z/13jKfz

Related