views::istream或ranges::istream_view的正确语法?



我正在尝试进入ranges::views.

下面的演示程序不能编译:

#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';
}
}

错误消息:

sArminsourcereposStackoverflowStackoverflowstackoverflow.cpp(21,56): error C2039: 'istream': is not a member of 'std::ranges::views'
1>C:Program Files (x86)Microsoft Visual Studio2019CommunityVCToolsMSVC14.29.30133includeranges(4051): message : see declaration of 'std::ranges::views'
1>C:UsersArminsourcereposStackoverflowStackoverflowstackoverflow.cpp(21,64): error C2275: 'CompleteLine': illegal use of this type as an expression
1>C:UsersArminsourcereposStackoverflowStackoverflowstackoverflow.cpp(10): message : see declaration of 'CompleteLine'
1>C:UsersArminsourcereposStackoverflowStackoverflowstackoverflow.cpp(21,5): error C2530: 'line': references must be initialized
1>C:UsersArminsourcereposStackoverflowStackoverflowstackoverflow.cpp(21,34): error C2143: syntax error: missing ';' before ':'
1>C:UsersArminsourcereposStackoverflowStackoverflowstackoverflow.cpp(26,15): error C2143: syntax error: missing ';' before ')'
1>Done building project "Stackoverflow.vcxproj" -- FAILED.

我使用的是"Microsoft Visual Studio Community 2019, Version 16.11.9";带有"预览-最新c++工作草案(/std:c++ Latest)">


有人能告诉我正确的语法上面的程序工作请?

P2432 (c++ 20 DR)允许我们通过自定义点对象views::istream来构造一个basic_istream_view对象。

但在此之前,我们需要调用自由函数istream_view(...)来获得basic_istream_view对象。

我怀疑您正在使用的MSVC版本尚未实现P2432,因此解决方法只是将views::istream替换为ranges::istream_view

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

最新更新