【问题标题】:Replace Macro with modern C++用现代 C++ 替换宏
【发布时间】:2021-03-11 22:14:15
【问题描述】:

我有以下宏

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

我想知道这是否可以用更现代的 c++ 代替,可以在头文件中一劳永逸地定义?

我的函数ErrorMsg有如下界面

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

【问题讨论】:

  • std::source_location 不幸的是 C++20。
  • 感谢您的提示!
  • 不知道source_location。谢谢@m88。我能想到的所有东西都会丢失__FILE____LINE__ 的正确值。可能是一些神秘的模板巫术,但我不擅长彻底的巫术。
  • 我认为 std::source_location 是要走的路我会标记 c++20,然后检查我们是否可以升级。 @m88 source_location 是否能够检测到它是从哪个行/文件/函数调用的,而无需明确提供?
  • 这是一个示例:godbolt.org/z/oWrMPW

标签: c++ c++20


【解决方案1】:

就像@m88 在 cmets 中所说,std::source_location 是获取文件名、函数名和行号的现代 C++ 方式 - 事实上,它是如此现代,以至于仅支持真正支持 C++ 的新编译器20.

这是一个同时执行宏方式和 std::source_location 方式的程序,以便您可以比较它们:

#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;
}

它产生:

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

试试https://godbolt.org/z/xdh4Y6

这是一个宏版本也可以打印函数名称的地方:

#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;
}

它产生:

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

试试https://godbolt.org/z/13jKfz

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-28
    • 1970-01-01
    • 2018-05-19
    • 2017-10-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多