我想写我自己的代表系统作为替代boost :: functions,因为后者做了很多堆分配,我认为是有问题的。
我写了这个作为替换(简化,实际的东西使用池式内存和安置新的,但,这是很简单的重现错误):
为什么在这种情况下C++模板参数推演失败?
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);
}
编译器错误时I g等对版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解决方案。
@RafaelSpring:是的,在C++之前11人曾经推出自己的身份包装。好东西。为了完整起见,在C++ 11中,有些人喜欢使用'template alias = T;',但这还没有增长。 –