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

后端 未结 8 2059
旧巷少年郎
旧巷少年郎 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:38

    There's no reason to do any run-time work for this:

    #include <iostream>
    
    // two macros ensures any macro passed will
    // be expanded before being stringified
    #define STRINGIZE_DETAIL(x) #x
    #define STRINGIZE(x) STRINGIZE_DETAIL(x)
    
    // test
    void print(const char* pStr)
    {
        std::cout << pStr << std::endl;
    }
    
    int main(void)
    {
        // adjacent strings are concatenated
        print("This is on line #" STRINGIZE(__LINE__) ".");
    }
    

    Or:

    #define STOP_HAMMER_TIME(x) #x
    #define STRINGIFICATE(x) STOP_HAMMER_TIME(x)
    

    If you're a cool person like James.

    0 讨论(0)
  • 2021-01-31 11:43

    Yes, it's ugly. You need a combination of macros. Converting an integer to a string is a two-step process - here's Boost's implementation:

    #define BOOST_STRINGIZE(X) BOOST_DO_STRINGIZE(X)
    #define BOOST_DO_STRINGIZE(X) #X
    

    Now you can generate a string:

    logError(__FILE__ BOOST_STRINGIZE(__LINE__) "testcondition failed");   
    
    0 讨论(0)
提交回复
热议问题