How to make preprocessor generate a string for __LINE__ keyword?

前端 未结 2 857
夕颜
夕颜 2021-02-02 08:10

__FILE__ is replaced with \"MyFile.cpp\" by C++ preprocessor. I want __LINE__ to be replaced with \"256\" string not with 256 integer. Without using m

2条回答
  •  半阙折子戏
    2021-02-02 08:59

    You need the double expansion trick:

    #define S(x) #x
    #define S_(x) S(x)
    #define S__LINE__ S_(__LINE__)
    
    /* use S__LINE__ instead of __LINE__ */
    

    Addendum, years later: It is a good idea to go a little out of one's way to avoid operations that may allocate memory in exception-handling paths. Given the above, you should be able to write

    throw std::runtime_error("exception at " __FILE__ " " S__LINE__);
    

    which will do the string concatenation at compile time instead of runtime. It will still construct a std::string (implicitly) at runtime, but that's unavoidable.

提交回复
热议问题