gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 14:31:04 25 4
gpt4 key购买 nike

我想编写记录器,并且需要有关源文件和行的数据。
此代码行是否在编译时起作用:

constexpr std::string_view source = (std::string(__FILE__) + ":" + std::to_string(__LINE__));
如果它在编译时不起作用,我该怎么办?也许不可能吗?

最佳答案

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

#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;
}

关于c++ - 编译时的C++字符串连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62577876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com