Default Template Parameters

Default Template Parameters

Rather than force you always to specify the Comp class explicitly, it would be nice to be able to default it to the most common case.

You can do this by supplying two function templates:

template<typename T, typename C>
	void sort(vector<T> &v);
template<typename T>
	void sort(vector<T> &v);

More conveniently, you can use default template parameters:

template<typename T, typename C = Comp>
void sort(vector<T> &v);

So, with some minor changes to a couple of files, and an additional file:

//
//  PolicySort.h
//  Function Overload Resolution
//
//  Created by Bryan Higgs on 10/13/24.
//

#ifndef PolicySort_h
#define PolicySort_h

#include <vector>
#include "PolicyCompare.h"

template<typename TYPE, typename C = Compare>
void sort(std::vector<TYPE> &v)
{
  size_t n = v.size();
  for (size_t i = 0; i < n - 1; i++)
  {
    for (size_t j = n - 1; i < j; j--)
    {
      if (C::compare(v[j], v[j - 1]) < 0)
      {  // swap v[j] and v[j-1]
        TYPE temp = v[j];
        v[j] = v[j-1];
        v[j - 1] = temp;
      }
    }
  }
}

#endif /* PolicySort_h */
//
//  ReverseCompare.h
//  Function Overload Resolution
//
//  Created by Bryan Higgs on 10/14/24.
//

#ifndef ReverseCompare_h
#define ReverseCompare_h

class ReverseCompare
{
public:
  static int compare(const char *s1, const char *s2)
  {
    return -strcmp(s1, s2);  // reverse compare
  }
};

#endif /* ReverseCompare_h */
//
//  PolicySort.cpp
//  Function Overload Resolution
//
//  Created by Bryan Higgs on 10/13/24.
//

#include <iostream>
#include "PolicySort.h"
#include "ReverseCompare.h"

void printVector(std::vector<const char *> v)
{
  for(int i = 0; i < v.size(); i++)
    std::cout << ' ' << v[i] << std::endl;
}

int main()
{
  std::vector<const char *> vstrs(10);
  
  vstrs[0] = "Vera";
  vstrs[1] = "mary";
  vstrs[2] = "fred";
  vstrs[3] = "Zena";
  vstrs[4] = "Algernon";
  vstrs[5] = "carol";
  vstrs[6] = "alan";
  vstrs[7] = "Richard";
  vstrs[8] = "Beatrice";
  vstrs[9] = "xavier";

  std::cout << "Before sorting: " << std::endl;
  printVector(vstrs);

  sort<const char *>(vstrs);
    
  std::cout << "After sorting: " << std::endl;
  printVector(vstrs);
  
  sort<const char *, ReverseCompare>(vstrs);
    
  std::cout << "After reverse sorting: " << std::endl;
  printVector(vstrs);

  return 0;
}

Which produces the following output:

Before sorting: 
 Vera
 mary
 fred
 Zena
 Algernon
 carol
 alan
 Richard
 Beatrice
 xavier
After sorting: 
 Algernon
 Beatrice
 Richard
 Vera
 Zena
 alan
 carol
 fred
 mary
 xavier
After reverse sorting: 
 xavier
 mary
 fred
 carol
 alan
 Zena
 Vera
 Richard
 Beatrice
 Algernon
Program ended with exit code: 0