0

This won't compile:

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;

Error as:

/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


Whereas, capture by reference is all okey.

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


Why does capturing rvalue of std::istringstream by value fail the Accumulateable concept?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
sandthorn
  • 2,770
  • 1
  • 15
  • 59

1 Answers1

2

Functors provided to all algorithms must be copyable. IOstream types are not copyable; they're move-only. And therefore, any lambda that contains them is not copyable.

Besides, you may as well be creating the istringstream inside the functor; clearing it and inserting a new string isn't exactly cheaper than constructing/destructing them in each cycle.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982