[英]C++20 string literal template argument working example
Could someone post a minimal reproducible example of C++20's feature string template as template argument?有人可以将 C++20 的特征字符串模板的最小可复制示例发布为模板参数吗?
this one from ModernCpp does not compile:这个来自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();
}
I've managed to write a working solution based on this Reddit post :我已经设法根据这个 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;
}
but does provide a custom implementation for a fixed string.但确实为固定字符串提供了自定义实现。 So what should be the state-of-the-art implementation by now?
那么现在最先进的实现应该是什么?
P0259 fixed_string
has been retired on the basis that most of its use cases are better achieved via P0784 More constexpr containers (aka constexpr destructors and transient allocation) - ie being able to use std::string
itself within constexpr context. P0259
fixed_string
已经退役,因为它的大多数用例都可以通过P0784 更好地实现更多 constexpr 容器(又名 constexpr 析构函数和瞬态分配) - 即能够在 constexpr 上下文中使用std::string
本身。
Of course, even if you can use std::string
in constexpr, that doesn't make it usable as an NTTP, but it doesn't look like we're going to get a structural string class into the Standard any time soon.当然,即使您可以在 constexpr 中使用
std::string
,也不能将其用作 NTTP,但看起来我们不会很快将结构字符串 class 纳入标准。 I would recommend using your own structural string class for now, being ready to alias it to an appropriate third-party class should one emerge in a popular library, or to a standard one if and when that happens.我建议现在使用您自己的结构字符串 class ,准备好将其别名为适当的第三方 class 以应对流行库中出现的问题,或者在发生这种情况时使用标准字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.