2016-12-28 18 views
0

假設我有這個類:傳遞不同的函數作爲參數

template<class K, class Compare> 
class findMax { 
    K* keyArray; // Supposed to be an array of K. 
    int size; 

public: 
     findMax (K n, Compare init); // Here I would like to initialize the array. 
     ~findMax(); 

     K& Find(K key, Compare cmp); // Return an elemnt in the array according to a condition. 
     void printArray(Compare print); // Print the array according to a condition. 

}; 

我希望每個cmp函數,當我實現構造,FindprintArray是不同的。
例如:

template<class K, class Compare> 
findMax<K, Compare>::findMax(int n, Compare init) { 
    keyArray = new K [n]; 
    init(keyArray, n); 
} 

其中init是一個功能我在源文件中實現,這樣的例子:

// Init will initialize the array to 0. 
void init (int* array, int n) { 
    for (int i=0; i<n; i++) 
     array[i] = 0; 
} 

雖然,我希望能夠發送不同的功能Find例如,比較兩個元素。我無法弄清楚如何,因爲當我創建一個新的findMax對象,如findMax<int, UNKNOWN> f,我該如何放置而不是UNKNOWN

+0

我有點被你有一個調用的函數混淆'init'類型的'Compare'初始化數據和一個類型也'Compare'比較數據。這真的是你想要的嗎? – doctorlove

+0

@doctorlove然後我該怎麼做?我如何將不同的功能傳遞給這個類?我的意圖是能夠使用源文件中的不同功能。 – SomeoneWithAQuestion

+0

[Function作爲模板參數傳遞]的可能重複(http://stackoverflow.com/questions/1174169/function-passed-as-template-argument) –

回答

1

試試這個 -

#include <iostream> 
#include <functional> 
using namespace std; 

template<class K, class Compare> 
class findMax { 
    K* keyArray; // Supposed to be an array of K. 
    int size; 

public: 
     findMax (K n, Compare init){init();}; // Here I would like to initialize the array. 
     ~findMax(){}; 
    template<typename Compare1> 
     K& Find(K key, Compare1 cmp){ cmp();}; // Return an elemnt in the array according to a condition. 
     template<typename Compare2> 
     void printArray(Compare2 print){print();}; // Print the array according to a condition. 

}; 
int main() { 
    findMax<int,std::function<void()>> a{5,[](){cout<<"constructor"<<endl;}}; 
    a.Find(5,[](){cout<<"Find"<<endl;}); 
    a.printArray([](){cout<<"printArray";}); 
    return 0; 
}