假设我有这门课程:
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
?
答案 0 :(得分: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;
}