C++ 范围-v3 : trying to chain together transforms

标签 c++ c++17 range-v3

我是 range 库的新手,所以这段代码没有编译我不应该感到惊讶,我也不知道为什么:

#include <iostream>
#include <algorithm>
#include <fstream>
#include <iterator>
#include <vector>

#include <range/v3/all.hpp>
#include <range/v3/view/all.hpp>
using namespace ranges::v3;


std::ifstream open_file(const std::string &filename) {
    return std::ifstream{filename};
}

int count_lines(std::ifstream &in) {
    return std::count(std::istreambuf_iterator<char>{in},
                      std::istreambuf_iterator<char>{}, '\n');
}

std::vector<int>
count_lines_in_files(const std::vector<std::string> &filenames) {
    auto a1 = filenames | view::transform(open_file) | view::transform(count_lines);
    return a1;
}

int main() {
    const std::vector<std::string> files{"listing1_1.cpp",
                                         "listing1_2.cpp",
                                         "listing1_4.cpp",
                                         "listing1_5.cpp"};
    const auto result = count_lines_in_files(files);
    std::cout << ranges::view::all(result) << '\n';
}

似乎投诉是关于 a1 的,编译器告诉我“错误:变量具有不完整的类型‘void’。”

谁能看出我做错了什么,或者告诉我如何在可能的情况下正确地将它们链接在一起?

提前致谢!

最佳答案

Porsche9II 所述,“std::ifstream 没有复制构造函数”。您可以在此处找到有关此主题的更多信息:

Why are iostreams not copyable?

C++11 为 std::basic_ifstream 引入了移动构造函数 ( 6 ),因此您可以编写

auto open_file(const std::string &filename) {
    return std::ifstream{filename};
}

auto count_lines(std::ifstream &&in) {
    return std::count(std::istreambuf_iterator<char>{in},
                      std::istreambuf_iterator<char>{}, '\n');
}

可测试 HERE .

关于C++ 范围-v3 : trying to chain together transforms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56285605/

相关文章:

c++ - 为什么 Boost Format 和 printf 在相同的格式字符串上表现不同

c++ - 有没有办法为用户定义的类型强制/建议 "statement has no effect"警告

c++ - 将vector <int8>转换为vector <uint8>

c++ - 链表显示乱码

c++ - 我的代码如何在编译时做一件事,而在运行时做另一件事?

c++ - 如何使用 range-v3 获取集合的所有权?

c++ - #define X X 在 C 中的作用是什么?

c++ - 链接 vector 类的问题

c++ - 你如何使用 range-v3 范围制作像 ranges::to<T>() 这样的可管道函数?

c++ - 如何用 range-v3 的范围填充 std::array?