Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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