如何打印#define语句?

时间:2010-12-21 01:03:39

标签: c++ macros c-preprocessor stringification

如何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();
  }
}

2 个答案:

答案 0 :(得分:4)

您需要使用stringize运算符:

throw runtime_error(# statement_);

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

答案 1 :(得分:1)

哦,我找到了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();
  }
}