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
函數,當我實現構造,Find
和printArray
是不同的。
例如:
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
?
我有點被你有一個調用的函數混淆'init'類型的'Compare'初始化數據和一個類型也'Compare'比較數據。這真的是你想要的嗎? – doctorlove
@doctorlove然後我該怎麼做?我如何將不同的功能傳遞給這個類?我的意圖是能夠使用源文件中的不同功能。 – SomeoneWithAQuestion
[Function作爲模板參數傳遞]的可能重複(http://stackoverflow.com/questions/1174169/function-passed-as-template-argument) –