【问题标题】:How to print the #define statement?如何打印#define 语句?
【发布时间】:2010-12-21 01:03:38
【问题描述】:

我怎样才能让cerr 打印5 < 6 而不是statement_?我可以使用 Boost 和 Qt。

using namespace std;

#define some_func( statement_ )               \
  if( ! statement_ )                          \
  {                                           \
    throw runtime_error( "statement_" );      \
  }                                           \

int main()
{
  try
  {
    some_func( 5 < 6 );
  }
  catch(std::exception& e)
  {
    cerr << e.what();
  }
}

【问题讨论】:

    标签: c++ macros c-preprocessor stringification


    【解决方案1】:

    你需要使用字符串化操作符:

    throw runtime_error(# statement_);
    

    如果statement_ 可能是一个宏,您将需要使用double stringize trick

    【讨论】:

      【解决方案2】:

      哦,我找到了this

      这是最终的工作代码 =):

      #include <stdexcept>
      #include <iostream>
      
      #define some_func( statement_ )              \
        if( ! statement_ )                         \
        {                                          \
          throw std::runtime_error( #statement_ ); \
      /* Note: #, no quotes!       ^^^^^^^^^^  */  \
        }                                          \
      
      int main(int argc, char** argv)
      {
        try
        {
          some_func( 5 < 6 );
        }
        catch(std::exception& e)
        {
          std::cerr << e.what();
        }
      }
      

      【讨论】: