boost::functions の代わりとして独自のデリゲート システムを作成しようとしています。これは、boost::functions が多くのヒープ割り当てを行うため、問題があるとプロファイルしました。
私はこれを代わりに書きました(単純化して、実際のものはプールされたメモリと新しい配置を使用しますが、これはエラーを再現するのに十分簡単です):
template<class A, class B>
struct DelegateFunctor : public MyFunctor {
DelegateFunctor(void (*fptr)(A, B), A arg1, B arg2) : fp(fptr), a1(arg1), a2(arg2) {}
virtual void operator()() { fp(a1, a2); }
void (*fp)(A, B); // Stores the function pointer.
const A a1; const B a2; // Stores the arguments.
};
およびこのヘルパー関数:
template<class A, class B>
MyFunctor* makeFunctor(void (*f)(A,B), A arg1, B arg2) {
return new DelegateFunctor<A,B>(f, arg1, arg2);
}
ここで奇妙なことが起こります:
void bar1(int a, int b) {
// do something
}
void bar2(int& a, const int& b) {
// do domething
}
int main() {
int a = 0;
int b = 1;
// A: Desired syntax and compiles.
MyFunctor* df1 = makeFunctor(&bar1, 1, 2);
// B: Desired syntax but does not compile:
MyFunctor* df2 = makeFunctor(&bar2, a, b);
// C: Not even this:
MyFunctor* df3 = makeFunctor(&bar2, (int&)a, (const int&)b);
// D: Compiles but I have to specify the whole damn thing:
MyFunctor* df4 = makeFunctor<int&, const int&>(&bar2, a, b);
}
バージョン C (B も同様) で発生するコンパイラ エラーは次のとおりです。
error: no matching function for call to ‘makeFunctor(void (*)(int&, const int&), int&, const int&)’
コンパイラがエラーメッセージで実際にタイプを正しく推定したため、これは奇妙です。
バージョン B をコンパイルする方法はありますか? boost::bind はこの制限をどのように回避しますか?
GCC 4.2.1 を使用しています。C++11 ソリューションはありません。