我想有一個函數根據給定的回調函數檢查某些條件。在C++中使用模板回調函數
認爲這代碼:
class Foo{
template <class ParamType>
struct IsGood
{
typedef bool (*Check)(typename const ParamType*, int other);
};
template< typename ParamType >
void DoSmth(IsGood<ParamType>::Check isGood, const ParamType* param){
//...
if(isGood(param, some_int_calculated_here)) doSmthElse();
}
我想是把它稱爲:
bool checkEqualInt(int* i, int j){return *i==j;}
bool checkEqualFloat(float* i, float j){return *i==j;}
DoSmth(checkEqualInt, &i);
DoSmth(checkEqualFloat, &i_float);
(所有構造例子來說明這個問題)
編譯器不會得到並拋出錯誤C2664「將bool(int *,int)中的參數1轉換爲bool(ParamType,int)不可能」
我有沒有使用
template< typename ParamType, Check >
void DoSmth(Check isGood, const ParamType param)
其中ommits的檢查功能的必要聲明的解決方案?
最好的解決方案是獲取函數本身的IsGood()頭。
我沒有看到最後一行纔回答。爲什麼使用代表仿函數的模板參數不是一個選項? – mfontanini
適用於我:http://ideone.com/czNr1e(在必要時添加/刪除'typename'後)。 – user2093113
@ user2093113'checkEqualFloat'雖然不起作用。 – mfontanini