我想寫我自己的代表系統作爲替代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;',但這還沒有增長。 –