boost::function_input_iterator

Boost 1.47.0からBoost.Iteratorに追加されるboost::function_input_iteratorを見てみました。


第1引数の関数オブジェクトを呼びながらN回進めるイテレータです。
以下の場合、[0, 3)の範囲の長さ分(つまり3回)だけ関数オブジェクトを呼び出します:

#include <iostream>
#include <algorithm>
#include <boost/iterator/function_input_iterator.hpp>

struct ones {
    typedef int result_type;

    result_type operator()() const
    {
        return 1;
    }
};

void disp(int x)
{
    std::cout << x << std::endl;
}

int main()
{
    ones ones_generator;
   
    std::for_each(
         boost::make_function_input_iterator(ones_generator, 0),
         boost::make_function_input_iterator(ones_generator, 3),
         disp
         );
}
1
1
1


無限の範囲がほしいときには、boost::infinite()を使用すればいいようです。この関数はで定義されます。

#include <iostream>
#include <utility>
#include <boost/iterator/function_input_iterator.hpp>
#include <boost/foreach.hpp>

struct ones {
    typedef int result_type;

    result_type operator()() const
    {
        return 1;
    }
};

int main()
{
    ones ones_generator;
   
    int i = 0;
    BOOST_FOREACH (int x, std::make_pair(
                    boost::make_function_input_iterator(ones_generator, boost::infinite()),
                    boost::make_function_input_iterator(ones_generator, boost::infinite())
                    ))
   {
       if (i > 10) // てきとうなところで抜ける
           break;
      
       std::cout << x << std::endl;
       ++i;
   }
}
1
1
1
1
1
1
1
1
1
1
1

ドキュメントでもあっさり"無限"を認めてしまってるので、
無限Rangeについてそれほど気にしなくてもいいのかもしれません。


これが実装される元になったチケットでも、無限についてそれほど議論されてなさそう。
https://svn.boost.org/trac/boost/ticket/2893