传递不同的函数作为参数

时间:2016-12-28 11:55:34

标签: c++ templates

假设我有这门课程:

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.

};

我希望在实现构造函数cmpFind时,每个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

1 个答案:

答案 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;
}