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

lee*_*ker 5 c++ string-view c++17

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

换一种方式:

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

你如何使用这些功能constexpr std::string_view?如果它们不能用于a constexpr std::string_view,为什么功能本身会被标记constexpr

Bar*_*rry 8

它们被标记的原因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);
Run Code Online (Sandbox Code Playgroud)

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


那说,我会写:

constexpr std::string_view a = "asdf"sv.substr(2);
Run Code Online (Sandbox Code Playgroud)

  • @inetknght不,不.`constexpr`成员函数不需要是`const`成员函数. (2认同)