c++ - std::string 最终会成为我们的编译时字符串吗?

标签 c++ constexpr stdstring idioms c++20

许多开发人员和库作者多年来一直在为编译时字符串苦苦挣扎——作为标准(库)字符串,std::string ,需要动态内存分配,而不是 constexpr。

所以我们有很多关于如何正确获取编译时字符串的问题和博客文章:

  • Conveniently Declaring Compile-Time Strings in C++
  • Concatenate compile-time strings in a template at compile time?
  • C++ Compile-Time string manipulation
  • (场外)Compile-time strings with constexpr

  • 我们现在了解到,new 不仅是可用 constexpr代码,允许在编译时动态分配,但实际上, std::string will become constexpr in C++20 (Herb Sutter 的 C++ 标准工作组 session 报告)。

    这是否意味着对于 C++20 及更高版本的代码,我们应该抛弃所有那些漂亮的编译时字符串实现,而总是使用 std::string ?

    如果不是 - 我们什么时候会这样做,我们什么时候会坚持今天的可能性(当然除了向后兼容的代码)?

    注意:我不是在谈论内容是其类型的一部分的字符串,即不是在谈论 std::integral_constant 的等价物。 ;那绝对不会是std::string .

    最佳答案

    这取决于您所说的“constexpr string”是什么意思。
    C++20 允许你做的是使用 std::string在标记为 constexpr 的函数中(或 consteval )。这样的函数可以创建一个string ,操纵它,等等,就像任何文字类型一样。但是,该字符串不能泄漏到非 constexpr代码;这将是一个非 transient 分配,是被禁止的。
    问题是,您提供的所有示例都是尝试使用字符串作为模板参数。这是一个相似但又不同的事情。您不只是在谈论在编译时构建字符串;你现在想用它来实例化一个模板。
    C++20 通过允许用户定义的类型作为模板参数解决了这个问题。但是对这种类型的要求比仅仅作为文字类型要严格得多。类型必须有 no non-public data members and the only members are of types that follow those restrictions .基本上,编译器需要知道其数据成员的逐字节比较代表一个等效值。甚至是 constexpr -有能力std::string不能那样工作。
    但是std::array<char, N>可以做到这一点。如果你在 constexpr代码,调用constexpr返回 std::string 的函数, 并将该字符串存储在 constexpr值,然后 string::size()constexpr功能。所以你可以用它来填写N为您的阵列。
    将字符复制到 constexpr array (因为它是 constexpr 值,所以它是不可变的)涉及更多,但它是可行的。
    所以 C++20 解决了这些问题,而不是(直接)使用 std::string .

    关于c++ - std::string 最终会成为我们的编译时字符串吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62852558/

    相关文章:

    c++ - 根据标准,这个 constexpr offset_of 的定义是否正确?

    c++ - boost:uuid 到 char * 没有 std::string

    c++ - 使用单个拷贝初始化 std::string

    c++ - boost spirit X3 解析器生成原始字符串的偏移量

    c++ - 如何在 Ubuntu 16.04 中安装 Eclipse C++ IDE?

    c++ - 使用 c++ 11 constexpr 进行 std::map 初始化

    c++ - 在 C++ 中将数字转换为具有指定长度的字符串

    c++ - MFC 项目组合 : How to add a SDI application without document class to a MDI application? 我应该使用子窗口吗?[MFC]

    c++ - C++中的实现

    c++ - 作为静态 constexpr 成员的类元素数组