I'm implementing a simple sort algorithm just to learn how C++ templates work. I need to sort arrays with elements of different types, so I need to use different functions of comparing them. For example, I want to sort the array of football players by their efficiency. I've written functor in with structure and use it in this way:
insertionSort(players, 0, players.size() - 1, Player());
But in insertionSort I need to pass comparator c to another function:
less(input[j], input[j-1], c); // can I do so?
Here is my code:
struct Player
{
int number;
ulong efficiency;
Player(int numb, ulong ef) : number(numb), efficiency(ef) {}
Player() : number(0), efficiency(0) {}
// functor for comparing players by efficiency
bool operator() (const Player &left, const Player &right)
{
return left.efficiency < right.efficiency;
}
};
// template function for comparing various elements
template<typename T, typename Comp = std::less<T> >
bool less (const T &left, const T &right, Comp c = Comp())
{
return c(left, right);
}
template <typename T>
void swap (T &a, T &b)
{
T tempr = a;
a = b;
b = tempr;
}
template<typename T, typename Comp = std::less<T> >
void insertionSort (vector<T>& input, int begin, int end, Comp c = Comp())
{
for (int i = begin; i <= end; ++i)
for (int j = i; j > begin && less(input[j], input[j-1], c); --j)
swap(input[j], input[j-1]);
}
Now I have the following compilation error: "default template arguments are only allowed on a class template" in function less and another template functions. Please, can you say, what I'm doing wrong? I can't find out where is my mistake. Thank you for your help!