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

标签 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();
}

我已经设法基于 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/

相关文章:

c++ - 是否有任何标准功能可用于创建以容器为 mapped_type 的 map 的平面 View ?

c++ - C++ 编译时调试

c++ - C++ 17 filesystem::recursive_directory_iterator()在Mac上没有此类目录给出错误但在Windows上有效

java - 使用 JNI 将数据从 Java 复制到 C++ 对象数组

c++ - 对不同类型使用具有不同返回值的模板函数不起作用

c++ - 函数重载和模板函数有什么区别?哪个更合适?

c++ - C++20 的内存模型与 C++11 的内存模型有何不同?

c++ - 为什么汇编时会出现 "Access violation reading location"错误?

c++ - 类型转换回存储在 char* 中的 int 值(0-255)给出负值

Java - 带有泛型参数的泛型类参数