Where is error with this template class? this code is from a c++ tutorial book.
-
@
#include <iostream>
using namespace std;// class templates
template <class T>
class pair {
T value1, value2;
public:
pair (T first, T second) {
value1=first;
value2=second;
}
T getmax ();
};template <class T>
T pair::getmax (){
T retval;
retval = value1>value2? value1 : value2;
return retval;
}int main () {
pair myobject (100, 75);
cout << myobject.getmax();
return 0;
}
@[edit: added coding tag @ SGaist]
-
Hi emas.
This is not a Qt question, i'll move it to right forum. -
Hi there,
you have some syntax problems there. The implementation of get max should be:
@template <class T> T pair<T>::getmax (){ T retval; retval = value1>value2? value1 : value2; return retval;
}@note the pair<T>::
The compiler can't infer the template parameter, so you need to provide it:
@ pair<int> myobject (100, 75); @Hope it helps,
H. -
//Thanks Arnaut, but it does not work either. qt creator says:
//D:\t\untitled9\main.cpp:25: error: reference to 'pair' is ambiguous, pair<int> myobject(100, 75);//the code is plain c++ project
@
#include <iostream>
using namespace std;// class templates
template <class T>
class pair {
T value1, value2;
public:
pair (T first, T second) {
value1=first;
value2=second;
}
T getmax ();
};template <class T>
T pair<T>::getmax (){
T retval;
retval = value1>value2? value1 : value2;
return retval;
}int main () {
pair<int> myobject(100, 75);
cout << myobject.getmax();
return 0;
}
@ -
Oh, I see.
The last problem is the using directive.
There is a class named pair in std namespace and the compiler can't decide between your class pair or the class std::pairHope it helps,
H.