I do an exercise and i wrote this code to test templates
#include <iostream>
#include "Date.h"
#include "Time.h"
using namespace std;
template <typename T>
bool compare(T first,T second){
if (first==second)
return true;
else
return false;
}
template <class T,class X>
bool compare(T first,X second){
if (first==second)
return true;
else
return false;
}
int main()
{
int a=1;
int b=2;
float c=1.1;
float d=1.11;
char e='k';
char f='k';
Date d1;
Date d2(26,8,1900);
Time t1;
Time t2(13,22,45);
if(compare(d1,d2))
cout<<d1<<" & "<<d2<<" are Equal!\n";
else
cout<<d1<<" & "<<d2<<" are not Equal!\n";
if(compare(t1,t2))
cout<<t1<<" & "<<t2<<" are Equal!\n";
else
cout<<t1<<" & "<<t2<<" are not Equal!\n";
if(compare(a,b))
cout<<a<<" & "<<b<<" are Equal!\n";
else
cout<<a<<" & "<<b<<" are not Equal!\n";
if(compare(c,d))
cout<<c<<" & "<<d<<" are Equal!\n";
else
cout<<c<<" & "<<d<<" are not Equal!\n";
if(compare(e,f))
cout<<e<<" & "<<f<<" are Equal!\n";
else
cout<<e<<" & "<<f<<" are not Equal!\n";
}
and works just fine.
my question is cause the book doesn't clarify it
at template definition here
template <class T,class X>
T compare(T first,X second){
if (first==second)
return true;
else
return false;
}
woudlnt be normal to be like that since the comparison objects are the same?
template <class T>
T compare(T first,T second){
if (first==second)
return true;
else
return false;
}
if i do this why i recieve that error
main.cpp: In function `int main()':
main.cpp:35: error: call of overloaded `compare(Date&, Date&)' is ambiguous
main.cpp:7: note: candidates are: bool compare(T, T) [with T = Date]
main.cpp:15: note: T compare(T, T) [with T = Date]
main.cpp:40: error: call of overloaded `compare(Time&, Time&)' is ambiguous
main.cpp:7: note: candidates are: bool compare(T, T) [with T = Time]
main.cpp:15: note: T compare(T, T) [with T = Time]
main.cpp:46: error: call of overloaded `compare(int&, int&)' is ambiguous
main.cpp:7: note: candidates are: bool compare(T, T) [with T = int]
main.cpp:15: note: T compare(T, T) [with T = int]
make[2]: Leaving directory `/cygdrive/c/Users/Haris/Documents/NetBeansProjects/Chapter 14/exercise 14.6 Operator Overload in Templates'
main.cpp:51: error: call of overloaded `compare(float&, float&)' is ambiguous
main.cpp:7: note: candidates are: bool compare(T, T) [with T = float]
main.cpp:15: note: T compare(T, T) [with T = float]
main.cpp:56: error: call of overloaded `compare(char&, char&)' is ambiguous
main.cpp:7: note: candidates are: bool compare(T, T) [with T = char]
main.cpp:15: note: T compare(T, T) [with T = char]