I’m templatizing a queue class so I can use it with anything from ints to whatever structs I need to define.
I need to pass a comparison function to the class constructor, a predefined comparison function for ints and alike then leave it up to the client to provide any comparison functions they may want. But how do I do this?
template<typename Type>
int cmpFn(Type one, Type two)
{
if (one < two) return -1;
if (one > two) return 1;
return 0;
}
template <typename Type>
class Queue
{
public:
Queue()
{
Type *list = new Type[size];
// What do I do now?
// How to define this constructor?
// It must pass a comparison function
// to a private sort method in this class.
}
private:
void sortFunc(Type list, int(fn)(Type one, Type two)=cmpFn);
};
There’s probably some mistakes in the above code since I just wrote it down from the top of my head to make my question more clear. But all I’m interested in is how to pass a comparison function to a sort method when defining a class.
This is a personal exercise, I’m not enrolled in any course nor have I access to any tutors. I’ve been googling this for a while now, but I couldn’t come up with the right answer… I guess I wasn’t asking the right question to Mr. Google.
P.S.
The client may want to provide comparison functions for any sort of data, like:
struct individual
{
string name;
int age;
double height;
};
I guess that the constructor has to be like this:
Queue(int (*fn)(Type, Type) = cmpFn);
But how do I define/implement this? It’s not a Queue object itself who will use this callback function, but its method: sort();
Here’s a working, compilable example of what I think you want:
Compiling and executing the program above should give you this output:
Basically what it does:
Queueconstructor accepts alistarray, its size and a callback function.cmpFn).sortFuncwhich loops though all the elements in thelistarray and compare them using the callback function.In the code above, you have an example with
intandstd::string.