假设我有这个类:
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
?
最佳答案
试试这个-
#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;
}
关于c++ - 传递不同的函数作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41361615/