Boost.Function アロケータをあとで設定する

boost::functionには、アロケータを指定する方法が用意されています。
ひとつはコンストラクタ。第1引数が関数オブジェクトで、第2引数がアロケータオブジェクトです。

template<typename F, typename Allocator>
function(F, Allocator);

もうひとつの方法は、assign()メンバ関数。代入演算子は引数がひとつしかないので、専用のメンバ関数が用意されています。ただしアンドキュメント。

template<typename F, typename Allocator>
void assign(F, Allocator);

これは以下のようにして使用します:

#include <cassert>
#include <memory>
#include <boost/function.hpp>

struct increment {
    int operator()(int x) const { return x + 1; }
};

int main()
{
    boost::function<int(int)> f;
    f.assign(increment(), std::allocator<increment>());

    assert(f(1) == 2);
}

これらを使うことで、boost::bind()と組み合わせることができますね。


assign()がアンドキュメントだという問題は、バグ報告しておきました。
アロケータを指定できる数少ない方法なので、ぜひドキュメントに記載してもらいたいですね。
#6962 - missing document function::assign()