【发布时间】:2019-12-31 10:22:59
【问题描述】:
是否可以将字符串存储在constexpr 结构中:
到目前为止,我只能想出:
struct A
{
constexpr A(std::string_view n): m_name(n) {}
constexpr auto name(){ return m_name; }
std::string_view m_name; // This might become dangling!!
}
如果这个类只像这样使用,这显然是个好主意
A a = {"Hello"};
constexpr A b = {"World"};
不是这样的
auto makeA(std::string n) { return A{n}; }
A a = makeA("Hello"); // Dangling internal std::string_view
我需要constexpr 在编译时构造结构。
是否有可能在运行时使其更安全,因为使用std::string_view,它不是。
【问题讨论】:
-
拍一个 "char_sequence",像 operator ""_cs 这样的东西可能会有所帮助。
-
制作 2 个相似类型怎么样。一个是
std::string_view,一个是std::string?在编译时使用std::string_view类型,在其他时候使用std::string类型。也许添加从编译时到运行时类型的隐式转换。 -
要使用 constexpr,您需要牢记编译器需要知道 constexpr 元素的最终值,否则它不能是 const。
标签: c++ string c++20 string-view