Template problems.

From: Val (valmont_gaming_at_hotmail.com)
Date: 12/28/03


Date: Sun, 28 Dec 2003 03:15:14 +0100

The code below has two classes:
One of them is doing a bubblesort. It uses the methods as declared (and
defined) in the IHandle class (or methods from derrrived classes from
IHandle, but nevermind that).
- BubbleSort::Sort() does not know what array-type it will sort.
-BubbleSort::IHandle* sortHandle is the handle to the IHandle class.
sortHandle will call the appr. methods from IHandle.
- IHandle class doesn not know what array-type it is going to get.
It will have later a purpose, but currently I am not getting this little
program to work decently.:

// **** ISortHandle.h ****

#ifndef ISORTHANDLE_H
#define ISORTHANDLE_H

template<class T> class ISortHandle
{
public:
 void SetArray(T* array, size_t size) { Array = array; ArraySize = size; }
 void Swap(T* lhe, T* rhe) { T temp; temp = *lhe; *lhe = *rhe; *rhe =
temp; }

 bool OutOfOrder(T* lhe, T* rhe) { return (*lhe < *rhe); }

private:
 T* Array;
 size_t ArraySize;
};

#endif //ISORTHANDLE_H

//**** BubbleSort.h ****

#ifndef BUBBLESORT_H
#define BUBBLESORT_H

#include "ISortHandle.h"

class BubbleSort
{
public:
 template <class S> void Sort(S* array, size_t size)
 {
  sortHandle->SetArray(array, size);
  for(int i = size; i>=0; --i)
  {
   for(int j= 0 ; j<size-1 ; j++)
   {
    if( sortHandle->OutOfOrder(sortHandle->Array[j],
sortHandle->Array[j+1]) )
     sortHandle->Swap(sortHandle->Array[j], sortHandle->Array[j+1]);
   }
  }
 }

public:
 BubbleSort() {}
  BubbleSort(ISortHandle* sort){ sortHandle = sort; }
private:
 ISortHandle* sortHandle;
};

#endif // BUBBLESORT_H

//**** main(): Our entry point for the application.

#include "ISortHandle.h"
#include "BubbleSort.h"
#include <iostream>
#include <string>

using namespace std;

int main()
{
 string sLeaderTypes[7]={ "President", "Queen", "Warlord", "Ceasar",
  "Minister", "Emperor", "Archduke"};

 ISortHandle* strSort=0;
 BubbleSort BSort(strSort);
 BSort.Sort(sLeaderTypes, 7);

 return EXIT_SUCCESS;
}

Can anyone make this happen? It's obviously a template thing but I am not
good with it. It's about time I do some practise. That's why.