确定没有宏的呼叫线路

elm*_*lmt 1 c++ macros c-preprocessor

是否可以在没有宏的帮助下确定调用函数的行号?

考虑以下代码:

#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;
}
Run Code Online (Sandbox Code Playgroud)

输出以下内容:

Line: 8
Line: 14
Run Code Online (Sandbox Code Playgroud)

我理解为什么每个人都会打印他们的作品 如果可以在不使用宏的情况下模仿宏功能,我会更感兴趣.

Bil*_*nch 6

我会做以下事情:

#define PrintLine() PrintLine_(__LINE__)

void PrintLine_(int line) {
    std::cout << "Line: " << line << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

我知道这并没有完全删除预处理器,但它确实将大部分逻辑移动到实际函数中.

  • 这是一个不错的解决方法,因为你*有*使用宏.但是,您应该在宏(:: PrintLine_或其所在的命名空间)中显式限定函数调用并使用括号. (3认同)