编译时的 C++ 字符串连接

Qui*_*zen 2 c++

我想编写记录器,我需要有关源文件和行的数据。这行代码在编译时是否有效:

constexpr std::string_view source = (std::string(__FILE__) + ":" + std::to_string(__LINE__));
Run Code Online (Sandbox Code Playgroud)

如果它在编译时不起作用,我将如何做?也许这是不可能的?

Mes*_*kon 10

这将在不分配的情况下工作,并且还编译时间

#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;
}
Run Code Online (Sandbox Code Playgroud)