C++ Function Templates

C++ Function templates are those functions which can handle different data types without separate code for each of them. For a similar operation on several kinds of data types, a programmer need not write different versions by overloading a function. It is enough if he writes a C++ template based function. This will take care of all the data types.

There are two types of templates in C++, viz., function templates and class templates. This article deals with only the function templates.

There are lot of occasions, where we might need to write the same functions for different data types. A favorite example can be addition of two variables. The variable can be integer, float or double. The requirement will be to return the corresponding return type based on the input type. If we start writing one function for each of the data type, then we will end up with 4 to 5 different functions, which can be a night mare for maintenance.

C++ templates come to our rescue in such situations. When we use C++ function templates, only one function signature needs to be created. The C++ compiler will automatically generate the required functions for handling the individual data types. This is how a programmer's life is made a lot easier.

C++ Template functions - Details:

Let us assume a small example for Add function. If the requirement is to use this Add function for both integer and float, then two functions are to be created for each of the data type (overloading).

int Add(int a,int b) { return a+b;} // function Without C++ template

float Add(float a, float b) { return a+b;} // function Without C++ template

If there are some more data types to be handled, more functions should be added.

But if we use a c++ function template, the whole process is reduced to a single c++ function template. The following will be the code fragment for Add function.

template

T Add(T a, T b) //C++ function template sample

{

return a+b;

}

This c++ function template definition will be enough. Now when the integer version of the function, the compiler generates an Add function compatible for integer data type and if float is called it generates float type and so on.

Here T is the typename. This is dynamically determined by the compiler according to the parameter passed. The keyword class means, the parameter can be of any type. It can even be a class.

C++ Template functions - Applicability:

C++ function templates can be used wherever the same functionality has to be performed with a number of data types. Though very useful, lots of care should be taken to test the C++ template functions during development. A well written c++ template will go a long way in saving time for programmers.

About The Author

Muthukumar

More articles can be found at http://www.codersource.net/.

shuttle to Midway Beardstown .. Lockport Chicago limo O’Hare
In The News:

The FBI has issued a warning that scammers are impersonating doctors, police and banks using spoofed numbers as "smishing" texts surge nationwide.
Communities with unreliable internet service stand to gain after Amazon's Project Kuiper launched its first full batch of satellites into orbit April 28.
Tech expert Kurt “CyberGuy" Knutsson says unsubscribing from spam might actually backfire. Learn when to avoid it and stop junk effectively.
Tech expert Kurt “CyberGuy" Knutsson talks about how the first nonstop beating heart transplant, called zero ischemic time, at Taiwan hospital changes surgery.
Kurt “CyberGuy" Knutsson: FBI warns of "time-traveling" hackers.
Kurt “CyberGuy" Knutsson talks about a soft, vine-like robot called SPROUT that aids safe survivor rescues in collapsed buildings.
Health insurance giant Blue Shield of California confirmed it had been sharing private health data of 4.7 million users with Google for three years without even realizing it.
Delta and JetZero’s blended wing body aircraft marks a meaningful step toward a cleaner, quieter and more efficient future for air travel.
Recent reports show many common passwords can be cracked in literally seconds. Kurt the CyberGuy explains how to strengthen your passwords.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Iron, a robot that stands 5 feet, 8 inches tall and weighs 154 pounds, combines advanced artificial intelligence with human-like movement and exceptional vision.
Hertz, the rental car giant, recently confirmed that customer information was exposed through a cyberattack on one of its software vendors.
There are a number of features with AirPods you may or may not know about to take your listening experience to the next level. Kurt the CyberGuy explains.
These 35 Chrome extensions have privacy and security concerns. Tech expert Kurt “CyberGuy" Knutsson says to delete them now.
Tech expert Kurt “CyberGuy" Knutsson says 329,000 mph fusion rocket promises to be fast, disruptive and enable deep-space missions.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Tech expert Kurt “CyberGuy" Knutsson says a new autonomous AI is a game changer that also raises privacy risks. Is your data safe?
Tech expert Kurt “CyberGuy" Knutsson says robots and drones are revolutionizing fruit farming with faster picking and smarter handling.
Landmark Admin revises May 2024 cyberattack scope to show twice as many people were affected. Kurt “CyberGuy" Knutsson gives tips to help stay safe from an insurance data breach.
Tech expert Kurt “CyberGuy" Knutsson talks about how Yamaha’s hydrogen outboard motor could revolutionize boating with zero emissions.
Tech expert Kurt “CyberGuy" Knutsson reveals how to memorialize or remove a deceased loved one’s Facebook account and protect their digital legacy from misuse or scams.
Tech expert Kurt “CyberGuy" Knutsson says an Apple Watch saved psychiatrist Amanda Faulkner by detecting deadly leukemia early.
Scammers and fraudsters are increasingly targeting the most vulnerable, especially nursing homes and the personal data of their residents. Kurt the CyberGuy has safety tips.
Infected USB flash drives can spread malware among multiple organizations in ways that can easily bypass traditional security systems.
With a fully automated warehouse system and AI-powered robots, Ocado's Hive picks, packs and delivers grocery store orders in just a few minutes.

Four Easy Ways To Prevent Spyware

How would you like to prevent spyware and adware from... Read More

Microsoft CRM Integration with Lotus Notes Domino: Messaging Connector ? Future Directions

IBM Lotus Notes Domino and Microsoft CRM (Client Relation Management)... Read More

Cisco Certification: Introduction To ISDN, Part III

Configuring PPP PAP AuthenticationNow we know how the ISDN link... Read More

Five Steps to Rapid Development with TierDeveloper 4.0

Follow the steps below to quickly design, generate, and deploy... Read More

What Stands Behind The Software Description?

With thousands of web pages added to the Net every... Read More

Interactive Mapping Brings Information to Life

What is Interactive Mapping?Interactive mapping is a visual display medium... Read More

Microsoft and Webmasters

Does Microsoft care for WebmastersIt's always been a problem with... Read More

Spyware Statistics -- Whats New in May 2005?

Although statistics often is blamed for various deadly sins --... Read More

S is for Spying, Surveillance -- and for Software as Well

Words we choose to describe things and phenomena often show... Read More

Passwords Used In Microsoft Word Documents

You would like to protect your documents, wouldn't you? Reasons... Read More

Protect Your Most Vital Business Asset with Security Software

Homeland security, airport security, Internet security ??" these days we???re... Read More

Snort for Network IDS

What is Snort?Snort is an open source network intrusion detection... Read More

Windows x: Basic Windows ?Security? Issues

Language development computer: Computer-based method for aiding language development seems... Read More

Behave, Word, Behave!

If you copy something from a Web site or elsewhere...... Read More

Microsoft CRM Messaging through Lotus Domino eMail Server - Balanced Solution

Microsoft CRM and IBM Lotus Notes Domino seem to be... Read More

What is Preventive Maintenance Software?

Preventive Maintenance (PM) is defined as scheduled work done on... Read More

OEComplete ? A Personal Information Manager

OEComplete is a utility for managing the personal information of... Read More

Microsoft RMS ? Great Plains Integration ? Overview For IT Specialist

Microsoft Great Plains and Microsoft Retail Management System (Microsoft RMS)... Read More

Five Reasons for Using an O/R Mapping Tool

So, why should you use any O/R mapping tool? I... Read More

Microsoft Great Plains Payroll Module Customization Scenarios

It is now common thing when large corporation selects mid-market... Read More

IT Strategy for Midsize Business: Microsoft vs. Java, Great Plains & CRM

Midsize business or non-profit organization should decide if one-vendor solution... Read More

How to Tell You Have Spyware, Ad-ware or Viruses

Usually, the easiest way to tell you have spyware is... Read More

Review of TikiWiki Content Management System

TikiWiki is open source software - it is written in... Read More

Save Your Resources - Combine Your IM Clients

There are so many different programs that clutter up your... Read More

Five Tips For A Great Software Demo

Whether you need to close a sale, gather end-user feedback,... Read More

Green Bay Hummer H2 SUV rentals ..