0

这不会编译:

auto acc_func = [iss{std::istringstream{}}](int acc, std::string &str) mutable {
    iss.str(str);
    int sz;
    iss >> sz;
    iss.clear();
    return acc + sz;

};
ranges::getlines_range lazy_lines = ranges::getlines(std::cin);
auto rng = lazy_lines | ranges::view::all;
auto begin = ranges::begin(rng);
auto end = ranges::end(rng);
auto acc = ranges::accumulate(begin, end, 0, acc_func);
std::cout << acc;

错误为:

/opt/compiler-explorer/libs/rangesv3/trunk/include/range/v3/numeric/accumulate.hpp:39:15: note: candidate template ignored: requirement 'Accumulateable<ranges::v3::_basic_iterator_::basic_iterator<ranges::v3::getlines_range::cursor>, int, (lambda at <source>:9:21), ranges::v3::ident>()' was not satisfied [with I = ranges::v3::_basic_iterator_::basic_iterator<ranges::v3::getlines_range::cursor>, S = ranges::v3::default_sentinel, T = int, Op = (lambda at <source>:9:21), P = ranges::v3::ident, _concept_requires_38 = 42]

            T operator()(I begin, S end, T init, Op op = Op{}, P proj = P{}) const

              ^

godbolt.org/g/3zjkLv


然而,通过引用捕获是没问题的。

std::istringstream stack_iss;
auto acc_func = [&iss{stack_iss}](int acc, std::string &str) mutable {
    iss.str(str);
    int sz;
    iss >> sz;
    iss.clear();
    return acc + sz;

};
ranges::getlines_range lazy_lines = ranges::getlines(std::cin);
auto rng = lazy_lines | ranges::view::all;
auto begin = ranges::begin(rng);
auto end = ranges::end(rng);
auto acc = ranges::accumulate(begin, end, 0, acc_func);
std::cout << acc;

godbolt.org/g/SbpH61


为什么按值捕获右值会使这个概念std::istringstream失败?Accumulateable

4

1 回答 1

2

提供给所有算法的函子必须是可复制的。IOstream 类型不可复制;他们只能移动。因此,任何包含它们的 lambda 都是不可复制的。

此外,您还可以创建istringstream仿函数的内部;清除它并插入一个新字符串并不比在每个周期中构造/破坏它们便宜。

于 2018-04-24T16:48:56.357 回答