Idiom for data aggregation and post processing in C++


A common task in programming is to process data on the fly and, when all data are collected, do some post processing. A simple example for this would be the computation of the average (and other statistics), where you can have a class like this

class Statistic {
public:
  Statistic() : nr(0), sum(0.0), avg(0.0) {}

  void add(double x) { sum += x; ++nr; }
  void process() { avg = sum / nr; }

private:
  int nr;
  double sum;
  double avg;
};

A disadvantage with this approach is, that we always have to remember to call the process() function after adding all the data. Since in C++ we have things like RAII, this seems like a less than ideal solution.

In Ruby, for example, we can write code like this

class Avg
  attr_reader :avg

  def initialize
    @nr = 0
    @sum = 0.0
    @avg = nil
    if block_given?
      yield self
      process
    end
  end

  def add(x)
    @nr += 1
    @sum += x.to_f
  end

  def process
    @avg = @sum / @nr
  end
end

which we then can call like this

avg = Avg.new do |a|
  data.each {|x| a.add(x)}
end

and the process method is automatically called when exiting the block.

Is there an idiom in C++ that can provide something similar?