Time remaining:
c++ programming

label Other
account_circle Unassigned
schedule 0 Hours
account_balance_wallet $5

what is template funtions


Nov 30th, -0001

In C++, function templates are functions that serve as a pattern for creating other similar functions. The basic idea behind function templates is to create a function without having to specify the exact type(s) of some or all of the variables. Instead, we define the function using placeholder types, called template type parameters. Once we have created a function using these placeholder types, we have effectively created a “function stencil”.

Creating function templates in C++:

 int max(int nX, int nY)

  {

  return (nX > nY) ? nX : nY;

  }

Note that there are 3 places where specific types are used: parameters nX, nY, and the return value all specify that they must be integers. To create a function template, we’re going to replace these specific types with placeholder types. In this case, because we have only one type that needs replacing (int), we only need one template type parameter. Let’s call our this placeholder type “Type”. You can name your placeholder types almost anything you want, so long as it’s not a reserved word. Here’s our new function with a placeholder type:

  Type max(Type tX, Type tY)

  {

    return (tX > tY) ? tX : tY;

  }

Using function templates:

Using a function template is extremely straightforward — you can use it just like any other function:

   int nValue = max(3, 7); // returns 7

   double dValue = max(6.34, 18.523); // returns 18.523

   char chValue = max('a', '6'); // returns 'a'

Note that all three of these calls to max() have parameters of different types!


Jul 19th, 2013

Did you know? You can earn $20 for every friend you invite to Studypool!
Click here to
Refer a Friend
...
Nov 30th, -0001
...
Nov 30th, -0001
Sep 20th, 2017
check_circle
Mark as Final Answer
check_circle
Unmark as Final Answer
check_circle
Final Answer

Secure Information

Content will be erased after question is completed.

check_circle
Final Answer