不使用宏确定呼叫线路
是否可以在不借助宏的情况下确定调用函数的行号?
考虑这段代码:
#include <iostream>
#define PrintLineWithMacro() \
std::cout << "Line: " << __LINE__ << std::endl; // Line 4
void PrintLine()
{
std::cout << "Line: " << __LINE__ << std::endl; // Line 8
}
int main(int argc, char **argv)
{
PrintLine(); // Line 13
PrintLineWithMacro(); // Line 14
return 0;
}
它输出以下内容:
Line: 8
Line: 14
我理解为什么每个人都会打印他们所做的事情。我更感兴趣是否可以在不使用宏的情况下模拟宏功能。
Is it possible to determine the line number that calls a function without the aid of a macro?
Consider this code:
#include <iostream>
#define PrintLineWithMacro() \
std::cout << "Line: " << __LINE__ << std::endl; // Line 4
void PrintLine()
{
std::cout << "Line: " << __LINE__ << std::endl; // Line 8
}
int main(int argc, char **argv)
{
PrintLine(); // Line 13
PrintLineWithMacro(); // Line 14
return 0;
}
which outputs the following:
Line: 8
Line: 14
I understand why each prints what they do. I am more interested if it's possible to mimic the macro function without using a macro.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我会执行以下操作:
我知道这并没有完全删除预处理器,但它确实将大部分逻辑移至实际函数中。
I would do the following:
I know that this doesn't completely remove the preprocessor, but it does move most of the logic into an actual function.
C++在c++20标准中已经赶上了这个问题。
在 c++20 中,您现在可以这样做:
另一个问题是您感兴趣的编译器是否已经赶上了标准。
请注意,该构造在 c++20 之前就已存在,您可以尝试:
C++ has caught up with this question in the c++20 standard.
In c++20 you may now do:
Another question is whether the compiler of your interest has caught up with the standard.
Note that the construct was present pre c++20 and you could try:
不便于携带。在任何给定的平台上,您基本上可以重新实现调试器的详细信息 - 该信息有效地存储在堆栈中作为返回地址。在某些平台上,您可以使用 backtrace() 函数来获得此类信息。
Not portably. On any given platform, you could basically re-implement the details of a debugger - the information is effectively stored on your stack as the return address. You can get at that kind of thing with the backtrace() function on some platforms.