Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use std::string_view::remove_prefix() on a constexpr string_view

std::string_view::remove_prefix() and std::string_view::remove_suffix() are both constexpr member functions in c++17; however, they modify the variable on which they are called. If the value is constexpr, it will also be const and cannot be modified, so how can these functions be used on a constexpr value?

To put it another way:

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

How do you use these functions on a constexpr std::string_view? If they can't be used on a constexpr std::string_view, why are the functions themselves marked constexpr?

like image 648
leecbaker Avatar asked Jun 26 '17 16:06

leecbaker


1 Answers

The reason they're marked constexpr is so you can use them within a constexpr function, e.g.:

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

If remove_prefix() weren't constexpr, this would be an error.


That said, I would write:

constexpr std::string_view a = "asdf"sv.substr(2);
like image 199
Barry Avatar answered Oct 22 '22 10:10

Barry