Templates!!!

Hello Guys!!!

Can anybody tell me the correct declaration of template functions and template constructors? I need syntax of these two templates.....Thanks!!!
closed account (zb0S216C)
http://www.cplusplus.com/doc/tutorial/templates/

Wazzak
I already checked this link but i don't understand the concept. Please tell me declaration in easy words.....
Imagine writing a function. Here's one:

1
2
3
4
int addTwoNumbers (int a, int b)
{
  return (a+b);
}


Now imagine that we want to have the same function, for a different type.

1
2
3
4
double addTwoNumbers (double a, double b)
{
  return (a+b);
}


The only difference between the two functions is the types. If only there was some way to tell the compiler that we want functions like this:

1
2
3
4
SOMETYPE addTwoNumbers (SOMETYPE a, SOMETYPE b)
{
  return (a+b);
}


and that the compiler will do the rest for us. This is what templates are for.

You simply write the function as normal, but on the front you put

template <class SOMETYPE>


and in your code you write the type that the compiler has to fill in for you as SOMETYPE,
so you get this:

1
2
3
4
5
template <class SOMETYPE>
SOMETYPE addTwoNumbers (SOMETYPE a, SOMETYPE b)
{
  return (a+b);
}


You can put whatever you like for SOMETYPE. Lots of people like to use T, like this:

1
2
3
4
5
template <class T>
T addTwoNumbers (T a, T b)
{
  return (a+b);
}


Then, every time we try to use a function called addTwoNumbers, like this:

addTwoNumber(7,5);

or

addTwoNumbers(someDoubleValue1, someDoubleValue2);

or

addTwoNumbers(someFloatValue1, someFloatValue2);

the compiler will make that function for us, using the template as a guide.

Last edited on
@Moschops Thanks 4 your reply....but how to declare template constructors? Any Syntax.....
Imagine you were writing a constructor.

It might look something like this:

1
2
3
4
someclass::someclass(int input)
{
   // ... all sorts of nice things in here
}


A template for that, which would have to be in a template class object, would look like this:

1
2
3
4
5
template <class T>
someclass<SOMETYPE>::someclass(int input)
{
  // ... all sports of nice thigns in here
}
Last edited on
@Moschops In template functions we have to declare template<class T> twice or just for one time. I mean separate for classes and functions...like this:
1
2
template<class T> //For Class
template<class Z> //For Member Functions 


Is this the correct method!!!
Topic archived. No new replies allowed.