简体   繁体   中英

C++ string concatenation in compile time

I want to write logger and I need data about source file and line. Does this line of code work in compile time or not:

constexpr std::string_view source = (std::string(__FILE__) + ":" + std::to_string(__LINE__));

If it doesn't work in compile time, how will I do it? Maybe is it impossible?

This would work without allocating, and also compile time

#include <iostream>

#define STR_(X) #X
#define STR(X) STR_(X)

int main() 
{
    //constexpr std::string_view(const char*) doesn't work in some versions of gcc, but is a better alternative if the compiler supports it
    constexpr const char* str = __FILE__ ":" STR(__LINE__);
    std::cout << str << std::endl;
}

If I get it right, __LINE__ and __FILE__ are Makros. Do this:

#define STRING(s) #s
constexpr std::string_view source = STRING(__FILE__) + ":" + STRING(__LINE__);

It should definetely work in compile time.


Update:

As mentioned in the comments, my approach will not work. Because STRING(__LINE__) will convert to "__LINE__" . So I need to do this:

#define _STRING(s) #s
#define STRING(s) _STRING(s)
constexpr std::string_view source = __FILE__ ":" STRING(__LINE__);

By the way, __FILE__ gives already back a char[], so I dont need to convert it and funfact: the compiler concatenates automatically adjacent strings, so I dont need the + either.

Thank you for pointing out the errors in my code. I leave the bug here, so others can learn from my mistakes too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM