【问题标题】:print variable name in a #define在#define 中打印变量名
【发布时间】:2011-10-14 10:07:33
【问题描述】:

我正在尝试使用宏在调试(日志记录)时将显示成员值的变量名称打印到控制台。 怎么做?我尝试了以下方法,但它不起作用。

#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
}

【问题讨论】:

  • 定义“它不起作用”。过去我也不得不对你说很多次,这很遗憾。
  • 嗨 Tomalek,请参阅下面的回复。添加'#'字符就足够了
  • 是的,我自己也知道答案。但我想训练你写正确的问题,有点晚了。
  • 好的。我不明白你的意图。

标签: c++ macros console-application


【解决方案1】:

啊……我找到了解决办法。

我应该这样写宏

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

【讨论】:

    【解决方案2】:

    对于 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;
    }
    

    这样编译器会根据数据类型来选择流操作符,所以你不需要为每个宏使用不同的宏,它可以去任何std::ostream,而不仅仅是std::cout。只需为您的数据提供适当的流式运营商:

    std::ostream operator<<(std::ostream&, const T&);
    std::ostream operator<<(std::ostream&, const std::vector<T>&);
    etc
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      • 1970-01-01
      • 2018-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-01-22
      相关资源
      最近更新 更多