c++ - 如何在 constexpr string_view 上使用 std::string_view::remove_prefix()

标签 c++ c++17 string-view

std::string_view::remove_prefix()std::string_view::remove_suffix() 都是 c 中的 constexpr 成员函数++17;但是,它们会修改调用它们的变量。如果值是 constexpr,它也将是 const 并且不能修改,那么这些函数如何用于 constexpr 值?

换句话说:

constexpr std::string_view a = "asdf";
a.remove_prefix(2); // compile error- a is const

如何在 constexpr std::string_view 上使用这些函数?如果它们不能在 constexpr std::string_view 上使用,为什么函数本身标记为 constexpr

最佳答案

它们被标记为 constexpr 的原因是您可以在 constexpr 函数中使用它们,例如:

constexpr std::string_view remove_prefix(std::string_view s) {
    s.remove_prefix(2);
    return s;
}

constexpr std::string_view b = remove_prefix("asdf"sv);

如果 remove_prefix() 不是 constexpr,这将是一个错误。


也就是说,我会写:

constexpr std::string_view a = "asdf"sv.substr(2);

关于c++ - 如何在 constexpr string_view 上使用 std::string_view::remove_prefix(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44764618/

相关文章:

c++ - 如何在不向标准 Ubuntu 版本安装额外库的情况下在 C++ 中拆分字符串?

c++ - 外部数组作为非类型模板参数与 clang c++1z

c++ - 拥有 [[nodiscard]] 类型的理由是什么?

c++ - string_view 和 basic_string<char> 有什么联系,为什么 string_view 示例代码不起作用?

c++ - 除了 std::string_view 方法之外, std::string_view 比 char* 有什么优势吗?

c++ - 成员构造函数和析构函数调用的顺序

c++ - 使用 boost::asio 获取 UDP 套接字远程地址

c++ - 如何使用 C++ 在没有 readline 的情况下显示字符串中的多个单词?

c++ - 保证省略和链式函数调用

c++ - 为什么sv后缀引入的字符串不会过期?