Home > Back-end >  Using replace with std::ranges::views
Using replace with std::ranges::views

Time:09-22

I am trying to learn ranges in C 20 using Microsoft Visual Studio 2019.

I created a function to make lowercase in a string and replace all spaces by '_'.

template <typename R>
auto cpp20_string_to_lowercase_without_spaces( R&& rng )
{
    auto view = rng
        | std::ranges::views::transform( ::tolower )
        | std::ranges::views::common;

    std::ranges::replace( view, ' ', '_' );
    return view;
}

And I got the following errors:

Error   C2672   'operator __surrogate_func': no matching overloaded function found  
Error   C7602   'std::ranges::_Replace_fn::operator ()': the associated constraints are not satisfied

I tried to use view.begin(), view.end() I tried to use the std::ranges::copy before call std::ranges::replace.

Is it something I am doing wrong?

PS: In the project settings, I had to select Preview - Features from the Latest C Working Draft (/std:c latest) because with ISO C 20 Standard (/std:c 20) with the latest version of Visual Studio 2019 preview I can't use views without compilation errors.

CodePudding user response:

transform creates a non-modifiable view. Specifically, it creates a range containing objects that are manufactured as needed. They have no permanent, fixed storage, so they cannot be "replaced" with something else.

You can copy the range into a container and then execute your replace operation on the container.

  • Related