C++20的std::source_location比预定义的宏__FILE__、__LINE__和__FUNCTION__有什么优势?

在我当前的项目中,我使用了:

Log(__LINE__, __FUNCTION__, message);

但是新的 C++20 实用程序类std::source_location
带有函数line(), column(), file_name(), function_name(),它们做同样的事情。因此,新的 C++20 方式将是:

log(std::string message,const std::source_location& location = std::source_location::current())
{
    std::cout << "Debug:"
              << location.file_name() << ':'
              << location.line() << ' '
              << message << 'n';
}

什么是新的,C ++ 20比旧标准双下划线宏方式的优点__LINE____FILE____func__,这已经被标准C ++很长一段时间?

我正在尝试确定优势是否如此之大,以至于证明修改我当前项目中的代码std::source_location以优先使用新对象而不是宏是合理的。

回答

在 C++20 之前,您必须在冗长(手动将__LINE__, __FILE__,传递__func__给每个调用)和使用宏为您做这件事之间做出选择。

std::source_location给你一个很好的调用语法,没有宏。没有其他隐藏的优势。

  • @AyxanHaqverdili You can't mimic `std::source_location::current()` in standard C++. Not without GCC's `__builtin_LINE()` or equivalent.
  • @Sneftel I misunderstood the answer initially. I thought the point was that it's a nicely packaged type. Looks like the point was you don't need to type `__LINE__` and other verbose macros.

以上是C++20的std::source_location比预定义的宏__FILE__、__LINE__和__FUNCTION__有什么优势?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>