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/.

house refresh service Lincolnshire ..
In The News:

Cybersecurity firm Infoblox reveals that over 90 percent of parked domains now redirect visitors to scams and malware, making simple typos extremely dangerous.
The Fox News AI Newsletter covers the latest artificial intelligence technology advancements, including the challenges and opportunities AI presents now and for the future.
GPT-5.2 is now live for all ChatGPT users with improved coding, writing and image interpretation, with Kurt Knutsson offering his review.
New iPhone replacement scam uses pressure tactics and fake carrier calls to steal devices from buyers. Criminals claim shipping errors and demand urgent returns.
Amazon Ring's new facial recognition feature sparks privacy controversy as Electronic Frontier Foundation critics argue the AI upgrade expands surveillance risks.
New Android banking trojan Sturnus steals credentials, reads encrypted messages and controls devices.
Denmark's 3D-printed student village proves automation builds 36 apartments faster than traditional methods. Skovsporet project shows housing future.
Discover Android's new Sound Notifications feature that alerts you to smoke alarms, doorbells, and baby cries even when wearing headphones.
New SantaStealer malware reportedly threatens holiday shoppers with password theft. This Christmas-themed info-stealer targets browsers and crypto wallets.
The Christmas season brings a surge in Netflix phishing scams targeting shoppers with fake emails. Stacey P received convincing scam but verified account first.
San Francisco Giants invite Jamie Grohsong to throw ceremonial first pitch at Oracle Park after he learned to play baseball with a bionic hand following an injury.
FBI warns cybercriminals are stealing family photos from social media to create fake proof of life images in virtual kidnapping scams targeting victims.
Instagram's new 'Your Algorithm' tool lets you control your Reels feed in real time. The app now gives you power to customize what videos you see.
Major Marquis fintech breach exposes 400,000-plus Americans' data through unpatched SonicWall vulnerability, with Texas hardest hit at 354,000 affected.
Free up iPhone storage fast by clearing large photos and videos from Messages app. Simple steps for iOS users to delete attachments without losing chats.
Scammers are flooding inboxes with fake tracking alerts that mimic real carriers, exploiting the holiday rush to steal logins and personal data.
The Fox News AI Newsletter brings you the latest news on AI technology advancements and the challenges and opportunities AI presents now and for the future.
Texas family reunites with missing 11-year-old cat Grayson after 103 days using Petco Love Lost's AI photo matching technology and community help.
Tired of AI customer service loops? These insider tricks help you escape "frustration AI" and get real human help when you need it most for urgent issues.
Unlock richer audio from your streaming apps with simple tweaks to volume normalization, equalizer settings, and quality preferences for cleaner sound.
Scammers are sending fake Facebook settlement payout emails that mimic legitimate notices from the privacy settlement administrator to deceive users.
Holiday shopping scams surge as fake refund emails target distracted consumers during Black Friday and holiday seasons, costing Americans billions annually.
The AI-powered IRMO M1 exoskeleton features four modes, including turbo, eco, training and rest for hiking, running, cycling and sports with eight-hour battery life.
OpenAI announced upgrades for its ChatGPT Images platform on Tuesday, saying the program can now make more precise edits and produce images more quickly.
Chrome for Android now turns web articles into AI-powered podcast conversations. Get hands-free browsing with Google Gemini's natural audio summaries.

Reduce TCO: The Java Database Way

TCO (Total Cost Ownership) is the buzzword in... Read More

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

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

Microsoft Great Plains eCommerce: overview for developer

Microsoft Business Solutions Great Plains was designed back in the... Read More

Microsoft Axapta, Navision or Great Plains: ERP Selection for Large Corporation

If you would like to pick something from Microsoft, or... Read More

CRM 101: Customer Relationship Management for Beginners

Customer Relationship Management, abbreviated "CRM," is the term for a... Read More

Oracle Development: JDeveloper 10G ? Java, J2EE, EJB, MVC, XML - Overview For Programmer

In 2004 Oracle, Inc. made its new step toward J2EE... Read More

Microsoft Great Plains Installation ? Overview for IT Director/Controller

Microsoft Great Plains is main mid-market application from Microsoft Business... Read More

FreeDOS

Before September 1995, Microsoft Windows was an MS-DOS program. DOS... Read More

Vlans

In order to implement VLANs in a network environment, you'll... Read More

Corporate Accounting System: Microsoft Great Plains ? Overview

Corporate ERP/MRP selection might be tough one, especially considering very... Read More

netstat - Linux Command to Display Networking Information

In linux, one of great commands for finding out information... Read More

Corporate ERP: Standard vs. Rich functionality ? Microsoft Great Plains

Traditionally we were considering functionally rich systems, such as SAP,... Read More

The Opera Alternative

Security flaws have long plagued Internet Explorer (IE), the market-dominating... Read More

Accounts Payable: A Powerful Document Management and Workflow Solution

Accounts payable is just one area of office management where... Read More

Anti-Spyware Protection ? Holes in the Shining Armor

Looking at all the ads which promise to get rid... Read More

Freight Forwarding ERP: Microsoft Business Solutions Great Plains customization & setup ? overview

Microsoft Great Plains may be recommended for international freight forwarding... Read More

Microsoft CRM Customization ? Programming Closed Email Activity

Microsoft CRM is CRM answer from Microsoft and attempt to... Read More

Selecting Corporate ERP: Microsoft Business Solutions Great Plains ? Estimation Parameters

As we could imagine, if you are reading this article... Read More

Why Stick With Email Clients Like Outlook?

Trying to figure out a stream in banning one email... Read More

A Simple Computer Software Definition

What is Software?Software is a set of instruction written to... Read More

SQL: Querying Microsoft Great Plains ? Overview for Database Administrator/Developer

Looks like Microsoft Great Plains becomes more... Read More

Microsoft Great Plains Customization Tools ? Overview

Former Great Plains Software Dynamics/eEnterprise, and currently Microsoft Business Solutions... Read More

Microsoft RMS Customization ? PO Items Receiving in Great Plains

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

Does your Company have Documentum?

Are you lost in the mess of documents that get... Read More

Lotus Notes Domino and Microsoft CRM Integration

Well, even if the combination might look very unusual, we... Read More

licensed cleaning services Lake Forest ..