First place I saw syntax I didn't understand was here.
template <typename T> int sgn(T val) {
return (T(0) < val) - (val < T(0));
}
Had a couple other small questions as I read this.
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
What I (think) I understand:
- Templates are used to help keep the DRY principle.
- Templates have the common attributes across classes that you want to be able to use.
Let's start with the first code example.
To me, it looks like there are two return types but I think I'm supposed to read it as "this is a template
function with <typename T>
where T
is the class. Therefore, only for this function, declare T
as a class which will be determined at compile time and will by the class called T
. This function will return an int
.
Is that a correct understanding of the function declaration? It seems strange to have to declare template <class T>
but it looks like when you have more than one template class you list them like so template <class T, class U>
.
Where in the code do we actually declare what attributes T
has and fit under that template? Is that what mypair
is being declared as in the next block? If I wanted mypair
to also be considered a U
would I just say template <class T, class U> class mypair {...
Second code example.
The specificate part I'm trying to understand is the declaration for getmax template <class T> T mypair<T>::getmax ()
I think mypair<T>::getmax()
is saying that we're declaring the getmax
function for mypair
. What does the T
in mypair<T>
refer to?
Final clarification question.
From what I read, it sounds like the main complaint about using templates is that they can increase compile time but it sounds like they have no impact on run time. Right?