[英]C++20 string literal template argument working example
有人可以将 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;
}
但确实为固定字符串提供了自定义实现。 那么现在最先进的实现应该是什么?
P0259 fixed_string
已经退役,因为它的大多数用例都可以通过P0784 更好地实现更多 constexpr 容器(又名 constexpr 析构函数和瞬态分配) - 即能够在 constexpr 上下文中使用std::string
本身。
当然,即使您可以在 constexpr 中使用std::string
,也不能将其用作 NTTP,但看起来我们不会很快将结构字符串 class 纳入标准。 我建议现在使用您自己的结构字符串 class ,准备好将其别名为适当的第三方 class 以应对流行库中出现的问题,或者在发生这种情况时使用标准字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.