Boost.Accumulatorsの動き

Boost.Accumulatorsの動きを把握するためのコードを書きました。

#include <iostream>
#include <limits>
#include <boost/accumulators/accumulators.hpp>
#include <boost/accumulators/statistics.hpp>

using namespace boost::accumulators;


struct integer {
    int x;
    integer() : x(0) {}
    integer(int x) : x(x) {}

    integer& operator+=(integer other)
    {
        std::cout << "+=,";
        x += other.x;
        return *this;
    }
};

namespace std {
    template <>
    struct numeric_limits<integer> {
        static const bool is_specialized = true;
        static ::integer max() { return std::numeric_limits<int>::max(); }
    };
}

integer operator+(integer a, integer b)
{
    std::cout << "+,";
    return integer(a.x + b.x);
}

integer operator-(integer a, integer b)
{
    std::cout << "-,";
    return integer(a.x - b.x);
}

integer operator*(integer a, integer b)
{
    std::cout << "*,";
    return integer(a.x * b.x);
}

integer operator/(integer a, integer b)
{
    std::cout << "/,";
    return integer(a.x / b.x);
}

bool operator<(integer a, integer b)
{
    std::cout << "<,";
    return a.x < b.x;
}

bool operator<=(integer a, integer b)
{
    std::cout << "<=,";
    return a.x <= b.x;
}

bool operator>(integer a, integer b)
{
    std::cout << ">,";
    return a.x > b.x;
}

bool operator>=(integer a, integer b)
{
    std::cout << ">=,";
    return a.x >= b.x;
}

bool operator==(integer a, integer b)
{
    std::cout << "==,";
    return a.x == b.x;
}

bool operator!=(integer a, integer b)
{
    std::cout << "!=,";
    return a.x != b.x;
}


int main()
{
    accumulator_set<integer, stats<tag::min, tag::mean, tag::sum> > acc;

    std::cout << "add:" << std::endl;
    acc(1);
    acc(2);
    acc(3);

    std::cout << std::endl;
    std::cout << "extract:" << std::endl;
    const integer a = extract::min(acc);
    const integer b = extract::mean(acc);
    const integer c = extract::sum(acc);

    std::cout << std::endl;
    std::cout << "result:" << std::endl;
    std::cout << a.x << std::endl;
    std::cout << b.x << std::endl;
    std::cout << c.x << std::endl;
}
add:
<,+=,<,+=,<,+=,
extract:
/,
result:
1
2
6

組み合わせによって必要なものだけが呼ばれているのと、要素を追加するたびに呼ばれる処理、抽出するときだけ呼ばれる処理、と分かれているのがわかります。


修正履歴:
2011/04/19 19:41 : minの結果が0になっていたので修正。1要素のときはnumeric_limits::max()と比較するようなのでintegerで特殊化。