How can I use the compile time constant __LINE__ in a string?

后端 未结 8 2139
旧巷少年郎
旧巷少年郎 2021-01-31 10:41

I can use __LINE__ as a method parameter just fine, but I would like an easy way to use it in a function that uses strings.

For instance say I have this:

8条回答
  •  忘了有多久
    2021-01-31 11:32

    std::string logError(const char* file, int line, const char* msg)
    {
       std::ostringstream os;
       os << file << ' ' << line << ':' << msg;
       return os.str();
    }
    

    Usage:

    return logError(__FILE__, __LINE__, "my error message");
    

    You could then make a macro for this if you were so inclined:

    #define LOG_ERROR(x) logError(__FILE__, __LINE__, (x))
    

    And then the usage would be:

    return LOG_ERROR("my error message");
    

提交回复
热议问题