C++20字符串文本模板参数工作示例

C++20 string literal template argument working example

本文关键字:工作 参数 字符串 文本 C++20      更新时间:2023-10-16

有人可以发布一个最小的可重现示例C++20的特征字符串模板作为模板参数吗?

这个来自ModernCpp的不编译:

template<std::basic_fixed_string T>
class Foo {
static constexpr char const* Name = T;
public:
void hello() const;
};
int main() {
Foo<"Hello!"> foo;
foo.hello();
}

我已经设法根据这篇Reddit帖子编写了一个工作解决方案:

#include <iostream>
template<unsigned N>
struct FixedString 
{
char buf[N + 1]{};
constexpr FixedString(char const* s) 
{
for (unsigned i = 0; i != N; ++i) buf[i] = s[i];
}
constexpr operator char const*() const { return buf; }
// not mandatory anymore
auto operator<=>(const FixedString&) const = default;
};
template<unsigned N> FixedString(char const (&)[N]) -> FixedString<N - 1>;
template<FixedString Name>
class Foo 
{
public:
auto hello() const { return Name; }
};
int main() 
{
Foo<"Hello!"> foo;
std::cout << foo.hello() << std::endl;
}

现场演示

但确实为固定字符串提供了自定义实现。那么,现在最先进的实施应该是什么?

P0259fixed_string已经退役,因为它的大多数用例都可以通过 P0784 更好地实现 更多的 constexpr 容器(又名 constexpr 析构函数和瞬态分配( - 即能够在 constexpr 上下文中使用std::string本身。

当然,即使你可以在 constexpr 中使用std::string,这也不能使它用作 NTTP,但看起来我们不会很快将结构字符串类放入标准中。我建议现在使用你自己的结构字符串类,如果流行库中出现一个,准备将其别名为适当的第三方类,或者如果发生这种情况,则将其别名为标准类。