Home > front end >  Correct syntax for views::istream or ranges::istream_view?
Correct syntax for views::istream or ranges::istream_view?

Time:12-19

I am trying to get into ranges::views.

The following demo program does not compile:

#include <iostream>
#include <sstream>
#include <string>
#include <iterator>
#include <ranges>
#include <algorithm>

namespace rng = std::ranges;

struct CompleteLine {    // Line Proxy for the input Iterator
    friend std::istream& operator>>(std::istream& is, CompleteLine& cl) { std::getline(is, cl.completeLine); return is; }
    operator std::string() const { return completeLine; }  // cast operator
    std::string completeLine{};
};

std::istringstream iss{ R"(1 Line AAA
2 Line BBB
3 Line CCC)" };

int main() {
    for (const std::string& line : std::ranges::views::istream<CompleteLine>(iss)
        | std::views::transform([](std::string line) {
            std::ranges::transform(line, line.begin(),
                [](auto c) { return std::tolower(c); });
            return line;
            })) {
        std::cout << line << '\n';
    }
}

Error messages:

s\Armin\source\repos\Stackoverflow\Stackoverflow\stackoverflow.cpp(21,56): error C2039: 'istream': is not a member of 'std::ranges::views'
1>C:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.29.30133\include\ranges(4051): message : see declaration of 'std::ranges::views'
1>C:\Users\Armin\source\repos\Stackoverflow\Stackoverflow\stackoverflow.cpp(21,64): error C2275: 'CompleteLine': illegal use of this type as an expression
1>C:\Users\Armin\source\repos\Stackoverflow\Stackoverflow\stackoverflow.cpp(10): message : see declaration of 'CompleteLine'
1>C:\Users\Armin\source\repos\Stackoverflow\Stackoverflow\stackoverflow.cpp(21,5): error C2530: 'line': references must be initialized
1>C:\Users\Armin\source\repos\Stackoverflow\Stackoverflow\stackoverflow.cpp(21,34): error C2143: syntax error: missing ';' before ':'
1>C:\Users\Armin\source\repos\Stackoverflow\Stackoverflow\stackoverflow.cpp(26,15): error C2143: syntax error: missing ';' before ')'
1>Done building project "Stackoverflow.vcxproj" -- FAILED.

I am using "Microsoft Visual Studio Community 2019, Version 16.11.9" with "Preview - Features from the Latest C Working Draft (/std:c latest)"


Can somebody tell me the correct syntax for the above program to work please?

CodePudding user response:

P2432 (C 20 DR) allows us to construct a basic_istream_view object through customization point object views::istream.

But before that, we need to invoke the free function istream_view(...) to get a basic_istream_view object.

I suspect that the version of MSVC you are using has not implemented P2432, so the workaround is just to replace views::istream with ranges::istream_view

for (const std::string& line : std::ranges::istream_view<CompleteLine>(is)
                             | std::views::transform([](std::string line) {
   // ...
}
  • Related