jeudi 29 décembre 2016

Emulate copy-assignment operator for lambdas in C++

This question has two parts

Firstly, can someone explain the rationale behind C++ disabling the copy-assignment operator for lambdas? If you're going to allow the copy constructor, why not the copy-assignment operator?

Secondly, how do you best overcome this limitation without forcing people to write C++03 style functors, or using std::function (the functions I'm dealing with are tiny, and I'd like the compiler to inline them wherever possible)?

Background: I'm trying to implement a flat_map like operation in a stream processing library I'm writing, similar to flatMap in Scala or other functional languages. As a result, I need to create an iterator that iterates over a list of iterators. Each time the flat_map iterator is de-referenced a lambda associated with the inner iterator is executed. The outer iterator needs to switch the inner iterator each time the inner iterator reaches the end. Since the inner iterator contains a lambda, and therefore does not have a copy-assignment operator, it's not possible to switch it. Technically I could solve the problem using dynamic allocation, so that I always call the copy-constructor, but that doesn't seem like the right approach. Here is a snippet of code that might help highlight the problem:

template <typename Iter>
class flat_map_iterator {
public:
  flat_map_iterator& operator++() {
    ++it_inner_;
    if (it_inner_ == (*it_outer_).end()) {
      ++it_outer_;
      // ERROR: cannot be assigned because its copy assignment operator is implicitly deleted
      it_inner_ = (*it_outer_).begin();
    }
    return *this;
  }
private:
  Iter it_outer_; 
  typename Iter::value_type::iterator it_inner_;
};

Aucun commentaire:

Enregistrer un commentaire