簡體   English   中英

傳遞不同的函數作為參數

[英]Passing different functions as arguments

假設我有這個課:

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.

};

在實現構造函數FindprintArray時,我希望每個cmp函數都不同。
例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM