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

premium house cleaning Arlington Heights ..
In The News:

A Facebook scammer posing as Elon Musk tricked a victim with promises of a Tesla and $250,000, requesting gift cards that become untraceable once the codes are shared.
Experience hands-free golfing with the Robera Neo smart caddie that uses AI to follow you, navigate obstacles and carry your clubs with GPS course mapping.
Cybersecurity alert: 16 billion passwords exposed in massive credential database affecting major platforms. Protect your accounts with password managers
The innovative BeBot robot uses electric power to remove pollution from shorelines, covering 20-30 times more area than manual collection while preserving wildlife.
A new ClickFix campaign targets macOS users with fake Spectrum support sites, tricking victims with CAPTCHA failures to paste commands that install information-stealing malware.
AI-powered autonomous trucks from Plus Automation are being tested across the U.S., Europe and Asia to solve logistics challenges while facing regulatory hurdles and labor concerns.
Your health information might feel private and secure with your doctor, but the reality is far more complicated. Data brokers collect a wide range of sensitive health data, from diagnoses and prescription details to personal identifiers, and sell this data to marketers, insurers, and other third parties.
Kepler Robotics has officially introduced its Forerunner K2 "Bumblebee" humanoid robot at the SAIC-GM automotive plant in Shanghai, marking a significant moment in the real-world deployment of advanced robotics.
Scammers never seem to be running out of new ways to try and get their hands on your money – and lately, they've been getting sophisticated.
Thirty people were injured and killed, though the exact number remains currently unknown, when a suicide bomber blew himself up in a Damascus church.
Unexpected password reset alerts signal potential hacking attempts or phishing scams. Learn how to respond and establish stronger security measures for your accounts.
A historic electric airplane flight landed at JFK with passengers, marking a milestone as Beta Technologies demonstrates the practicality and efficiency of electric air travel.
The Chaos ransomware group breached Optima Tax Relief in a double-extortion attack, stealing sensitive customer case files and corporate documents with personal information.
Stay up to date on the latest AI technology advancements and learn about the challenges and opportunities AI presents now and for the future.
The first human brain-computer interface by Paradromics was completed in 20 minutes, featuring microelectrodes to help paralyzed individuals control computers with thoughts.
The power behind AI tools requires massive energy, and global data centers are expected to triple electricity usage by 2030 despite tech companies' renewable pledges.
New Android malware Crocodilus spreads through Facebook ads disguised as banking apps, adds fake contacts to phones and steals financial data with advanced screen monitoring.
ANYmal-D, the badminton-playing quadruped robot from ETH Zurich, combines artificial intelligence with whole-body coordination to rally with human players for up to 10 shots.
A personal data protection guide revealing 10 signs your information is circulating among data brokers and practical strategies to regain control of your digital footprint.
New Android security updates include smarter scam detection, Key Verifier for identity confirmation, Find Hub tracking and Advanced Protection to safeguard your phone and data.
Tech expert Kurt “CyberGuy" Knutsson reports that scammers made a fake Venmo that mimics a real cancer nonprofit’s handle.
Tech expert Kurt “CyberGuy" Knutsson says Hugging Face has launched affordable open-source humanoid robots for home AI exploration.
Tech expert Kurt “CyberGuy" Knutsson tells how one person almost fell for a phishing scam despite strong security. Learn to spot and stop scammers.
Tech expert Kurt “CyberGuy" Knutsson takes a look at the Mercedes Vision V luxury van and its 65-inch screen, 42 speakers and first-class comfort.
A third-party dental marketing agency's unsecured database exposed millions of patient profiles with personal information that could be exploited for identity theft and insurance fraud.

Corporate Accounting System: Microsoft Great Plains ? Overview

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

The Importance of Timely Timesheets

Whether you are a small consultancy firm, a medium sized... Read More

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

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

Great Plains Dexterity: Customizations & Source Code Programming

Great Plains Software Dynamics, Dynamics C/S+, eEnterprise were written on... Read More

Microsoft Great Plains: Interest Calculation Example ? Stored Procedure for Crystal Report

This is intermediate level SQL scripting article for DB Administrator,... Read More

Microsoft and Webmasters

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

Microsoft Great Plains: Customization Upgrade & Recovery ? Visual Studio VB 6.0

Microsoft Great Plains, former Great Plains Software Dynamics, eEnterprise has... Read More

Lotus Notes Domino and Microsoft CRM Integration

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

Great Plains Custom Development: Dexterity, VBA, SQL, Crystal, eConnect ? Overview For Programmer

Microsoft Great Plains is main Microsoft Business Solutions accounting package... Read More

Free Preventive Maintenance Software

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

Basic Steps To Optimize Your Internet Security

After seeing many people complain about their weak Internet security... Read More

How To Develop Software For Your Business

Software development is a risky business.Many software developers are barely... Read More

Collaboration Software: Index of Collaboration Software Technologies

Collaboration SoftwareCollaboration Software, also known as group collaboration software or... Read More

Software Engineering: An Introduction

Software Engineering is the Systematic Approach for analysis design implementation... Read More

Great Plains Dynamics on Pervasive/Ctree support ? overview for consultant

All of us know that Microsoft bought former Great Plains... Read More

Lotus Domino/Notes - Microsoft Great Plains Tandem as ERP with Documents Workflow - Overview for IT

Lotus Domino/Notes ? Microsoft Great Plains tandem as ERP with... Read More

Builders Beware

Which Type of Shop Can Rely On A Home Built... Read More

Is Your Family Protected?

When you think... Read More

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

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

Managing Stress in the Computer Industry - Five Steps to a Stress-free Life

It would be easy to think, like most people apparently... Read More

Causes of ERP Failures

ERP is the acronym of Enterprise Resource Planning. Multi-module ERP... Read More

C++ Function Templates

C++ Function templates are those functions which can handle different... Read More

Scrap Booking Online: Word Perfect or Corel Graphics Suite?

Scrapbooks are very popular these days. I think that almost... Read More

Why Java RDBMS?

It is a well known fact that Java as a... Read More

Microsoft CRM: Implementation, Customization, Support ? Consultant Overview

Microsoft Business Solutions CRM is present several years on the... Read More

eco-friendly cleaning service Deerfield ..