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

5

std::string_view::remove_prefix()std::string_view::remove_suffix()是c++17中的两个constexpr成员函数;然而,它们会修改被调用的变量。如果这个值是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

1个回答

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);

如果remove_prefix()不是constexpr,那么这将是一个错误。
即便如此,我也会写成:
constexpr std::string_view a = "asdf"sv.substr(2);

1
这个说法有道理,但实际上函数是 constexpr void remove_prefix(size_type)。你能在 constexpr 中使用一个唯一目的是改变现有对象的方法吗? - Useless
@Useless 我所回答的代码正是这样做的。我同意它很奇怪。 - Barry
是的,我完全误读了你的自由函数。在GCC7.1中它实际上对我不起作用,但我猜这对于1z来说还为时过早。 - Useless
@Useless 是的,我也注意到了 - libstdc++ 的 remove_prefix() 实现没有标记为 constexpr - Barry
constexpr 意味着 const,不是吗?所以 std::string_view::remove_prefix() 不应该能够修改自身吧? - inetknght
2
@inetknght 不需要。constexpr 成员函数不需要是 const 成员函数。 - Barry

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接