将字符串存储在constexpr结构中 [英] store a string in a constexpr struct
问题描述
是否可以将字符串存储在 constexpr
结构中:
Is it possible to store a string in a constexpr
struct:
到目前为止,我只能提出:
So far I could only come up with:
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!!
}
这显然是一个好主意,如果此类仅仅使用
which is cleary only a good idea if this class is only used like this
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
却不是.
I need the constexpr
to construct the struct at compile time.
Is it possible to make this safer at run-time, because with std::string_view
, its not.
推荐答案
您可以这样做:
template<typename Char, Char... Cs>
struct CharSeq
{
static constexpr const Char s[] = {Cs..., 0}; // The unique address
};
// That template uses the extension
template<typename Char, Char... Cs>
constexpr CharSeq<Char, Cs...> operator"" _cs() {
return {};
}
在在编译时进行字符串实习以进行分析,查看我的答案,如果有 MAKE_STRING
宏,您不能使用扩展名(实际上更冗长,并且对可接受的字符串长度进行硬编码限制).
See my answer from String-interning at compiletime for profiling to have MAKE_STRING
macro if you cannot used the extension (Really more verbose, and hard coded limit for accepted string length).
然后
struct A
{
template <char ... Cs>
constexpr A(CharSeq<char, Cs...>) : m_name(CharSeq<char, Cs...>::s) {}
constexpr auto name(){ return m_name; }
std::string_view m_name;
};
仅具有类似于以下内容的有效用法:
With only valid usages similar to:
A a = {"Hello"_cs};
constexpr A b = {"World"_cs};
这篇关于将字符串存储在constexpr结构中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!