我有以下宏
#define Error(error_msg) ErrorMsg(__FILE__,__LINE__,error_msg)
Run Code Online (Sandbox Code Playgroud)
我想知道这是否可以用更现代的 c++ 替换,它可以在头文件中一劳永逸地定义?
我的功能ErrorMsg有以下界面
void ErrorMsg(const std::string &file, int line, const std::string &report)
Run Code Online (Sandbox Code Playgroud)
就像@m88 在评论中所说的那样,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;
}
Run Code Online (Sandbox Code Playgroud)
它产生:
info: ./example.cpp:23: Hello World
info: ./example.cpp(23:62) `int main()` Hello World
Run Code Online (Sandbox Code Playgroud)
在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;
}
Run Code Online (Sandbox Code Playgroud)
它产生:
info: ./example.cpp(27) `int main()` Hello World
info: ./example.cpp(27:62) `int main()` Hello World
Run Code Online (Sandbox Code Playgroud)
在https://godbolt.org/z/13jKfz尝试一下