A step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.
Creating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.
Basics of function templatesThis tutorial covers the basics of using function templates in C++. It shows you how to create them and explains how they work. |
On Tuesday, October 26th 2004 at 11:01 AM By Andrew Pociu (View Profile) ![]() ![]() ![]() ![]() (Rated 3.4 with 13 votes) |
|||||||
What are function templates used for?Suppose you have a function that returns the sum of two numbers stored in two variables. The variables are passed as parameters (arguments). The parameters are of type int, so the function would look like this:
But what if I want to add two doubles? The function accepts only int's, what can I do? Well here the function template comes into play.
Probably you already know what this code does and how function templates work. The first thing you noticed is perhaps the following line:
This line creates a - let's say -universal type called AnyType. Older versions of C++ don't understand the template
Moving on into the code you can see that we replaced the int parameters of the function with AnyType:
Now depending on which parameters we will pass to the Add() function, AnyType will change to the type that fits the parameters. For example if we pass ints, the AnyType keyword will be replaced with int. But if we pass doubles like we did, AnyType will become double:
So now you know that the actual use of function templates is to pass diferent types of variables to the same function, using function calls, like this:
Function templates improve performance?No, using function templates you don't get any improved performance. For example in the code above the compiler will actually create two versions of the function, one with int parameters and one with double. The only gain is the programmer's time. |
||||||||
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
||||||||
|
||||||||
Current Commentsthis pages is ok. as u hav not given the template use for string. and not deal with objects. only u deal with 2 variable that of same type . but i think in a tutorial you should give some thing more.
Its very basic article, I was searching an implementation of template in C (not C++)
Related Tutorials
Related Source Code
C++ Job Search