是否可以使作为默认参数的宏在调用站点扩展?

pul*_*ser 1 c++ macros default-arguments c++11 std-source-location

#include <stdio.h>

void print(int a = __LINE__){printf("hello %d\n", a);}

void main(){
  print();
  print();
  print();
  print();
}
Run Code Online (Sandbox Code Playgroud)

本例中的宏__LINE__扩展为 3,因此使用相同的值调用 print 函数 4 次。有没有办法说服编译器在调用点扩展此宏,以便使用 C++11 中存在的功能6,7,8,9而不是调用 print 函数?3,3,3,3

我的用例:

在我的应用程序中,我提供了多个采用唯一 ID 的函数。每个调用站点/位置的 ID 应该是唯一的(因此,如果通过同一语句调用该函数两次,它应该收到相同的 id)。目前,用户始终必须LOCATION在调用站点手动键入宏,如下所示:

#define S1(x) #x //voodoo to concat __FILE__ and __LINE__
#define S2(x) S1(x)
#define LOCATION __FILE__ S2(__LINE__)

do_stuff1(arguments, LOCATION)
do_stuff2(arguments, LOCATION)
Run Code Online (Sandbox Code Playgroud)

如果我可以节省他们的打字时间,而不需要为每个函数创建宏,如下所示,那就更方便了:

#define do_stuff1(do_stuff1_imp(arguments, LOCATION))
#define do_stuff2(do_stuff2_imp(arguments, LOCATION))
Run Code Online (Sandbox Code Playgroud)

因此我认为默认参数可以解决问题。有什么办法可以实现这一点吗?

Jus*_*tin 5

您似乎正在寻找std::experimental::source_location,它将出现std::source_location在未来的标准中:

#include <experimental/source_location>

void print(std::experimental::source_location const& location
    = std::experimental::source_location())
{
    printf("hello %s:%d\n", location.file_name(), location.line());
}
Run Code Online (Sandbox Code Playgroud)

  • 这确实正是我一直在寻找的。不过我将无法使用 C++17(我认为这需要吗?)。抱歉,我忘了在问题中提到这一点。不过,我会在未来牢记这一点。谢谢! (2认同)