support << operator in a macro

前端 未结 1 1953
自闭症患者
自闭症患者 2021-01-28 15:57

I\'d like to implement a macro which does the following:

#define report(s)   print(), throw std::runtime_error(s)

print() is a fun

相关标签:
1条回答
  • 2021-01-28 16:33

    Perhaps the following (untested!) code might be inspirational

    #define report(Log) do { std::ostringstream _os; \
      _os << Log << std::flush; print(_os.str()); \
      throw std::runtime(_os.str()); } while(0)
    

    and you might use it as report("x=" << x);

    BTW, you might even pass the source location using

    #define report_at(Log,Fil,Lin)  do { std::ostringstream _os; \
      _os << Fil << ":" << Lin << ": " << Log << std::flush; \
      print(_os.str()); \
      throw std::runtime(_os.str()); } while(0)
    

    (to lower probability of collision with _os you might even replace all its occurrences inside the brace with _os##Lin using preprocessor concatenation)

    #define report_at_bis(Log,Fil,Lin) report_at(Log,Fil,Lin)
    
    #define report(Log) report_at_bis(Log,__FILE__,__LINE__)
    

    and this shows one of the cases where a macro is really useful.

    0 讨论(0)
提交回复
热议问题