How to Create a Template in C++




(5.00 out of 5)



(5.00 out of 5)



(5.00 out of 5)



(5.00 out of 5)



(5.00 out of 5)



(5.00 out of 5)



(5.00 out of 5)





How to Create a Template in C++
Log in to answer.
Copyright © dBuggr LLC - All Rights Reserved.
nishantbaxi 12:27 am on July 22, 2010
1.Declare the template by typing text below. myType, TemplateName, variable1, and variable2 can be named anything you want. myType will represent a type that hasn’t been identified, TemplateName will represent the name of your template, and variable1 and variable2 will represent the variables to be used in your function template. Note that you can have as much variables as you want.
template
myType TemplateName(myType variable1, myType variable2)
{
};
2.Begin programing your code within the brackets. It should involve the variables you defined (in the example above they would be variable1 and variable2). Here’s a sample template: template
T GetMax (T a, T b) {
T result;
result = (a>b)? a : b;
return (result);
}
Note that you have to use T whenever you make a variable.
Calling the Template
1.Create some variables in the main body of your code.
2.Type your template name and the type of the variable within angle brackets. In we were using integers with our example, we would type:
int i=2, j=3, k;
k=TemplateName(i,j);