Classes with template

Hi,i tried to write a code to compare the classes with templates but this code is not working.I think i shoul use operators but i don't know how to write it in my code.Can anyone help?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
#include "stdafx.h"
#include <iostream>

using namespace std;
class STUDENT
{
	int ID;
public:
	STUDENT(int IDın):ID(IDın)
	{}
	int GetId()
	{
		return ID;
}
};
template < class X > class MIN
{
	X var;
public:
	X GetMin(X a,X b)
	{
		return a<b ? a:b;
	}
};

int _tmain(int argc, _TCHAR* argv[])
{
	

	STUDENT st1(10);
	STUDENT st2(15);
	MIN<STUDENT&>m2;
	cout << m2.GetMin(st1,st2).GetId()<<endl;

	return 0;
}
You need to overload operator< in STUDENT class.

1
2
//since student only has an ID, compare ID's
bool operator<(const STUDENT& a){return (ID<a.ID)}

Last edited on
Also references are not always practical types for template parameters.

Example:
MIN<STUDENT&>m2; //template type is a reference.

That would mean that in the STUDENT class:
1
2
3
4
5
6
7
8
9
10
11
template < STUDENT & >  //*****with STUDENT& as the parameter type 
class MIN
{
      //****When the compiler tries to instantiate the class - You will have the following line:    
  STUDENT & var;  //Problem here - see explanation below  
public:
    X GetMin(X a,X b)
    {
        return a<b ? a:b;
    }
};


When a class declaration contains a reference variable - the compiler will refuse to
make a default constructor - for obvious reasons.
References have to be initialized in an initialization list.


So just do:
MIN<STUDENT>m2;

Also you will need the overloased < (less than) operator for the STUDENT class - as already suggested by naraku9333
Last edited on
How can you call it in the main function then??
this (MIN<STUDENT>m2;) gives an error like "no appropriate default constructer available".

i still can't compare the classes.
That problem is due to this line (in the MIN CLASS):
X var;

This is because the STUDENT class has a constructor that takes parameter - which
means that in order to do STUDENT var you need a default constructor.
If you provide a constructor that take parameters then you (the programmer) has to provide
a default constructor as the compiler won't do it for you.

So add a default constructor to the STUDENT class.


Then that will leave the operator < overload function for the STUDENT to be done.
I deleted X var and then it is solved.
Thanks lot to guestgulkan and naraku9333..
Topic archived. No new replies allowed.