C++20字符串文本模板参数工作示例
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;
}
现场演示
但确实为固定字符串提供了自定义实现。那么,现在最先进的实施应该是什么?
P0259fixed_string
已经退役,因为它的大多数用例都可以通过 P0784 更好地实现 更多的 constexpr 容器(又名 constexpr 析构函数和瞬态分配( - 即能够在 constexpr 上下文中使用std::string
本身。
当然,即使你可以在 constexpr 中使用std::string
,这也不能使它用作 NTTP,但看起来我们不会很快将结构字符串类放入标准中。我建议现在使用你自己的结构字符串类,如果流行库中出现一个,准备将其别名为适当的第三方类,或者如果发生这种情况,则将其别名为标准类。
相关文章:
- 如何使我的 sizeof sum 结构与空参数包一起工作
- 如何定义在用作函数参数时工作的类模板的转换
- C++20字符串文本模板参数工作示例
- C++中的可变参数模板及其工作原理
- std::bind,无法让具有单个参数的方法工作
- 隐式转换是否应该在模板参数的上下文中工作?
- 我不明白参数和参数如何协同工作
- 通过参数启用时,std::enabled_if 如何工作
- 当传递NULL作为参数时,函数重载是如何工作的
- GoogleTest 中的参数化测试无法按预期工作
- 此函数如何在不传递任何参数的情况下工作?
- 我的代码在作为参数传入 .begin() 时不起作用,但在我将 .begin() 转换为迭代器后工作
- C++11: 如何编写一个像 Get 一样工作的模板函数<tuple>...但是收到参数包?
- 参数传递和返回值如何在程序集级别的 x86 上的 C/C++ 中工作?
- 我可以更改将引用参数传递到指针中并使其正常工作的函数的输入(C、C++)吗?
- 工作函数重载如何使用可变参数解析?
- 宏参数的扩展如何在 c++ 中工作
- 错误太多参数无法正常工作
- 具有可变参数的std ::函数列表如何工作
- C++参数化构造函数使代码在传递大输入时停止工作