有人可以将 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();
}
我已经设法基于 this Reddit post 编写了一个有效的解决方案:
#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;
}
Live Demo
但确实为固定字符串提供了自定义实现。那么现在最先进的实现应该是什么?
最佳答案
P0259 fixed_string
已retired基于它的大多数用例可以通过 P0784 More constexpr containers 更好地实现(又名 constexpr 析构函数和 transient 分配) - 即能够使用 std::string
本身在 constexpr 上下文中。
当然,即使你可以使用std::string
在 constexpr 中,这并不能使其用作 NTTP,但看起来我们不会很快将结构字符串类纳入标准。我建议现在使用您自己的结构字符串类,准备好在流行库中出现时将其别名为适当的第三方类,或者如果发生这种情况时将其别名为标准类。
关于C++20 字符串文字模板参数工作示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62266052/