0

Suppose I have this class:

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.

};

I want each cmp function to be different when I implement the constructor, Find and printArray.
For example:

template<class K, class Compare>
findMax<K, Compare>::findMax(int n, Compare init) {
    keyArray = new K [n];
    init(keyArray, n);
}

where init is a function I implement in my source file, like this for example:

// Init will initialize the array to 0.
void init (int* array, int n) {
    for (int i=0; i<n; i++)
        array[i] = 0;
}

Although, I want to be able to send a different function to Find for example, that compares between two elements. I'm having trouble figuring out how because when I create a new findMax object, like findMax<int, UNKNOWN> f, what do I put instead of UNKNOWN?

  • I'm a bit confused by you having a function called `init` of type `Compare` to initialise data and one also of type `Compare` to compare data. Is this really what you want? – doctorlove Dec 28 '16 at 11:59
  • @doctorlove How do I do it then? How can I pass different functions to this class? My intention is to be able to use different functions from the source file. – SomeoneWithAQuestion Dec 28 '16 at 12:01
  • Possible duplicate of [Function passed as template argument](http://stackoverflow.com/questions/1174169/function-passed-as-template-argument) – o_weisman Dec 28 '16 at 12:05

1 Answers1

1

Try this -

#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;
}
user1438832
  • 493
  • 3
  • 10