gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 01:26:52 28 4
gpt4 key购买 nike

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com