在#define中打印变量名

Abr*_*ile 6 c++ macros console-application

我试图在调试(日志记录)时使用宏来显示控制台,显示成员值的变量名称.怎么做?我尝试了以下但它不起作用.

#define MY_PRINT(x) std::cout << "'x'=" << x << std::endl;

int main(){
   int my_variable=3;
   MY_PRINT( my_variable );
   // I would like to print to console
   // 'my_variable'=3
}
Run Code Online (Sandbox Code Playgroud)

Abr*_*ile 18

奥奇...我找到了解决方案.

我应该像这样写宏

 #define MY_PRINT(x) std::cout << #x"=" << x << std::endl
Run Code Online (Sandbox Code Playgroud)


sho*_*nho 5

对于 C++,我使用这个:

#define STR(x) #x << '=' << x

int main()
{
  int i = 1;
  std::string str("hello");
  std::vector<std::string> vec;
  my_class mc;

  ...

  std::cout << STR(i) << std::endl
            << STR(str) << std::endl
            << STR(vec) << std::endl
            << STR(mc) << std::endl;

  return 0;
}
Run Code Online (Sandbox Code Playgroud)

这样,编译器会根据数据类型选择流操作符,因此您无需为每个操作符使用不同的宏,并且它可以转到任何 std::ostream,而不仅仅是 std::cout。只需为您的数据提供适当的流式操作符:

std::ostream operator<<(std::ostream&, const T&);
std::ostream operator<<(std::ostream&, const std::vector<T>&);
etc
Run Code Online (Sandbox Code Playgroud)

但我希望有一种模板方法来替换宏,或者至少替换 #x 提供的变量名称。