Skip to content

Instantly share code, notes, and snippets.

@fabiogaluppo
Last active December 8, 2015 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fabiogaluppo/c128606504709b1c7566 to your computer and use it in GitHub Desktop.
Save fabiogaluppo/c128606504709b1c7566 to your computer and use it in GitHub Desktop.
template<typename T>
struct accumulator_with_predicate final
{
using UnaryPredicate = std::function<bool(T)>;
explicit accumulator_with_predicate(T init, UnaryPredicate pred)
: acc(init), pred(pred) {}
accumulator_with_predicate& operator+(const T& val)
{
if (pred(val)) acc += val;
return *this;
}
operator T() const { return acc; }
accumulator_with_predicate() = delete; //default-constructible
accumulator_with_predicate(const accumulator_with_predicate&) = default; //copy-constructible
accumulator_with_predicate& operator=(const accumulator_with_predicate&) = default; //copy-assignable
~accumulator_with_predicate() = default; //destructor
private:
T acc;
UnaryPredicate pred;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment