2016-12-28 43 views
-3

假設我有這個類:傳遞函數的一類

template<class K, class func1, class func2> 
class findMax { 
    K* key; 
    func1 cmp; 
    func2 areSame; 
}; 

template<class K, class func1, class func2> 
findMax<K, func1, func2>::findMax(K n, func1 isValid, func2 areSameFunc) { 

    cmp = isValid; 
    areSame = areSameFunc; 
} 

如何使這個類的一個實例?
我曾嘗試:

typedef bool (*someFunc)(int); 
typedef bool (*someFunc2)(int, int); 

findMax<int, someFunc, someFunc2> u(7, isValid, areSame); // Doesn't compile, error below. 

錯誤消息:

Invalid arguments ' 
Candidates are: 
findMax(const findMax<int,bool (*)(int, int),bool (*)(int)> &) 
findMax() 
findMax(int, #10000, ?, ?) 
' 

其中:

bool isValid (int k) { 
    return (k>0); 
} 

bool areSame (int key, int key2) { 
    return key==key2; 
} 

但是,這是行不通的。我也試過其他方法,但無法找到如何做到這一點。
那我該怎麼做呢?

+1

什麼不行? – Carcigenicate

+0

@Carcigenicate對不起,添加。 – SomeoneWithAQuestion

+0

@SomeoneWithAQuestion在C++代碼中使用'std :: function'。 –

回答

1

你需要理清你的構造函數聲明/定義,可能也是你的會員的聲明(它可能應該是一個值,而不是一個指針)。因此,它應該直接創建對象。

就個人而言,我不會真的都指定模板參數而是創建一個合適的工廠函數。例如:

template<typename K, typename Fun1, typename Fun2> 
class findMax { 
    K  key; 
    Fun1 cmp; 
    Fun2 areSame; 
public: 
    findMax(K n, Fun1 isValid, Fun2 areSameFunc) 
     : key(n) 
     , cmp(isValid) 
     , areSame(areSameFunc) { 
    } 
}; 

template<typename K, typename Fun1, typename Fun2> 
findMax<K, Fun1, Fun2> makeFindMax(K n, Fun1 fun1, Fun2 fun2) { 
    return findMax<K, Fun1, Fun2>(n, fun1, fun2); 
} 

bool isValid (int k) { 
    return (k>0); 
} 

bool areSame (int key, int key2) { 
    return key==key2; 
} 

int main() { 
    auto obj = makeFindMax(7, isValid, areSame); 
} 
+0

感謝您的回答。 findMax實際上是在一個頭文件中,我發佈的其餘代碼位於源文件中。有沒有一種方法,我可以做到這一點,而不必從我的源文件調用另一個函數來創建一個新的'findMax'? – SomeoneWithAQuestion

+0

@SomeoneWithAQuestion:在頭文件中聲明工廠函數也沒有錯。然而,一旦你正確地定義了你的構造函數,你可以像在makeFindMax()中那樣調用它。 –