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

Moi*_*oia 6 c++ templates c++20

有人可以将 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();
}
Run Code Online (Sandbox Code Playgroud)

我已经设法根据这篇 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;
}
Run Code Online (Sandbox Code Playgroud)

现场演示

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

eca*_*mur 6

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

当然,即使您可以std::string在 constexpr 中使用,这并不意味着它可以用作 NTTP,但看起来我们不会很快将结构字符串类纳入标准。我建议现在使用您自己的结构字符串类,准备好将其别名为适当的第三方类(如果出现在流行的库中),或者在出现这种情况时将其别名为标准类。