vendredi 29 avril 2016

Iterator-reducer pattern for functions that may or may not return a value

The following function applies a functor on each element and reduces the return value:

template <class FCT, class RED>
RED::TYPE forAllElements(FCT functor, RED reducer){
  for(/* all elem in elements */){
    reducer(functor(elem));
  }
  return reducer.value;
}

Now, sometimes I might wish to just call the functor on all elements, and not reduce anything. Basically, I would then like to have something like:

class FunctorThatReturnsNothing{
  void operator() (Elem e){
    // do something, return nothing...
  }
}

class DummyReducer{
  using TYPE = void; // ??? something like that ???

  template <class FCT>
  void operator() (/* ??? what here */){
    // do nothing...
  }
}

forAllElements(FunctorThatReturnsNothing(), DummyReducer());

But that won't compile since I have reducer(functor(elem)) where the non-existent return value of a void function is taken as an argument.

Is there a way to make it work for void functors without duplicating forAllElements for a void and a non-void case?

(For people suspecting an XY-Problem: I basically know different approaches for iterating and reducing and I think that the presented callback approach is appropriate for my case. I just wonder how I can avoid to have duplicate code for the "return value + reducing" and the "just callback" case.)

Aucun commentaire:

Enregistrer un commentaire