Reputation: 277
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?
Upvotes: 4
Views: 937
Reputation: 196
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.
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.
Upvotes: 3
Reputation: 4046
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;
}
Upvotes: 12