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

last minute cleaning help Arlington Heights ..
In The News:

Fox News Digital's artificial intelligence newsletter digs into a robot in Russia that faceplanted, George Clooney's alarm and OpenAI's rivalry with the New York Times.
Major data breach at Conduent exposes personal information of 10+ million people. Government contractor hit by cyberattack affecting Medicaid, child support systems.
Texas startup Janta Power raises $5.5M for innovative vertical solar towers that generate 50% more energy than traditional panels while using just one-third the land.
NASA's twin ESCAPADE spacecraft launched aboard Blue Origin's New Glenn rocket Thursday afternoon from Cape Canaveral, beginning their journey to Mars with arrival expected in 2027.
Learn how to set email reminders on iPhone and Android so you never forget to reply again. Simple built-in features help you stay organized and on top of messages.
Discover how Apple's passkeys revolutionize Mac security by replacing vulnerable passwords with biometric authentication and encryption for ultimate protection.
New survey reveals 78% of parents fear AI scams targeting their kids, yet nearly half haven't discussed these threats. Learn why this dangerous gap exists.
Chrome now autofills passport and driver's license info automatically. Google's latest browser update adds official document support with encryption and user control.
Scammers impersonate Department of Veterans Affairs employees claiming veterans owe money, but real VA communications only direct to VA.gov or official channels.
The AltoVolo Sigma hybrid-electric aircraft flies 500 miles at 220 mph while operating 80% quieter than helicopters, featuring safety systems and compact design.
Google search scam alert: fake customer service numbers can give scammers remote control of your phone. Learn how to spot these traps and protect yourself.
Electric vehicles overtake gas cars in total CO2 savings after just two years of driving, with emissions benefits growing over time as power grids get cleaner.
Louvre Museum reportedly used "Louvre" as password for surveillance system during $100M jewel heist. Learn how weak passwords put even famous institutions at risk.
Bipartisan AI jobs bill from Sens. Hawley and Warner would require companies to report AI-related layoffs and hiring to Department of Labor quarterly.
Joe A. from Shelton, Connecticut, lost $228,000 to a ZAP Solutions cryptocurrency investment scam after his divorce, highlighting rising online fraud.
AI-powered autonomous trucks from Waabi and Volvo target U.S. freight driver shortage with Level 4 self-driving technology and NVIDIA computing platform integration.
Survive flight disruptions with expert travel tips: Book early morning flights, download airline apps and know your refund rights during service cuts.
Apple's iOS 26.1 update delivers major security fixes, performance boosts and enhanced privacy controls for your iPhone. Discover why updating now protects your data.
Russian hackers use fake CAPTCHA tests to spread dangerous malware targeting governments and journalists. Learn how to protect yourself from these deceptive attacks.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
Miami-Dade debuts America's first autonomous police SUV with AI cameras, drone deployment and real-time crime detection in groundbreaking law enforcement pilot.
Bank impostor scams cost Americans $2.9 billion as criminals use AI voices and caller ID spoofing to steal life savings. Learn nine essential fraud protection tips.
Foreign-owned apps secretly harvest personal data from seniors, making them prime targets for scams. Learn how to protect your privacy and stop data brokers today.
Sens. Josh Hawley and Richard Blumenthal introduce bipartisan GUARD Act to protect minors from AI chatbots through mandatory age verification and disclosure requirements.
Ghost-tapping scammers exploit wireless technology to drain accounts through small transactions, but RFID-blocking wallets and transaction alerts can protect you.

Recent Studies Show that 9 out of 10 PCs Are Infected with Spyware

Spyware and malware are large problems for Internet users today... Read More

MCP Market News: Microsoft SQL Server & SQL Reporting Services

Are you ready? SQL Server 2005, the next-generation data management... Read More

Groove Network. Are you in it?

If you are in a business that passes documents around... Read More

Quick Summary of Basic and Common Linux Commands

There are many commands that are used in linux on... Read More

The Dirt on Screensavers

Remember back in the days where screensavers were the coolest... Read More

Software: What Suits Me?

Almost all new and major brand of PCs come with... Read More

Microsoft CRM Data Conversion FAQ

Microsoft Business Solutions CRM data conversion deserves FAQ type of... Read More

Crystal Reports - Geterogeneus databases: SQL Server, Oracle, Unidata, Btrieve ? Tips For Developer

Crystal Reports is the most flexible tool on the market... Read More

Microsoft Great Plains: Manufacturing or Bill of Materials - Overview for IT Specialist

Microsoft Great Plains is main Microsoft Business Solutions product, targeted... Read More

Lotus Notes Domino and Web: Application Development ? Tips for Programmers

Beginning with Domino version R4 it has integration with the... Read More

Things You Can Do With Windows XP!

Did you ever give a thought to the number of... Read More

Internet Security Threats: Who Can Read Your Email?

Before being able to choose a secure Internet communication system,... Read More

Lowering The Risks In Developing Do-It-Yourself Software Projects

Mike Dunville* had a decision to make. As the new... Read More

PHP On-The-Fly!

IntroductionPHP can be used for a lot of different things,... Read More

Free Preventive Maintenance Software

While several preventive maintenance software manufacturers offer free trials for... Read More

Computer Phones ? Facts and Fallacies

The stakes are high when considering security, privacy, and savings,... Read More

Microsoft CRM Implementation for Large Corporation ? overview

Microsoft Business Solutions CRM is now approaching the phase of... Read More

The Secret of the Layer Styles Dialogue

When you double-click a layer in the Layer Palette, you... Read More

.NET :Solving the Multiple Inheritance Issue Under .NET Platform

.NET platform does not support multiple inheritance. Do not confuse... Read More

Microsoft Great Plains: carpet, textile, fabric, felt distributor ? implementation overview

In this small article we will show you the possible... Read More

Microsoft Great Plains Integration with Microsoft Access ? Overview for Developer

... Read More

Groupware: Answers the 5 Questions of Document Collaboration

Every organization which creates collaborative documents, whether they are budgets,... Read More

Can You Calculate Complex Financial Calculations?

Are you a whiz at calculating financial information? Not the... Read More

Microsoft Great Plains: Offshore Customization & Development ? Overview for Consultant

When you visit department stores and see that majority of... Read More

Microsoft and Webmasters

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

same day cleaning service Wilmette ..