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

In The News:

Investigators Probe Software's Role In Deadly Boeing 737 Max Crashes  NPRThe probe of two Boeing plane crashes is focused, for the moment, on software. We examine how software has become a common fix for problems with ...
View: Transforming India through Software Products 2.0  ETtech.comWhile India invests in developing a strong local ecosystem, it should also continue to encourage global companies to invest in R&D and scientific capa..
Boeing to offer safety feature as standard in 737 MAX software upgrade: Sources  Moneycontrol.comBoeing will mandate a previously optional cockpit warning light as part of a software update to the 737 MAX fleet that was grounded in the wake of the fatal ...
Our Expectations Of Software Have Changed -- It's Time UX Caught Up  ForbesLast year, I argued that many enterprise software vendors are missing the point when it comes to user experience. They aim to embrace user expectations by ...
4 Software Stocks for Growth Investors to Snap Up in 2019  Zacks.comHere we select four software stocks, displaying strong growth potential, to add to your portfolio right away.
Here’s What Beta Systems Software AG’s (FRA:BSS) Return On Capital Can Tell Us  Simply Wall StToday we are going to look at Beta Systems Software AG (FRA:BSS) to see whether it might be an attractive investment prospect. Specifically, we're going to ...
Despite short-term questions, games software/hardware to top $200 billion by 2023  TechCrunchThere has been some negative sentiment surrounding the games industry recently, with stock prices of public games companies in question in both the U.S. and ...
Nvidia's Datacenter Chief Talks to TheStreet About AI and Its Software Edge  TheStreet.comIan Buck, who oversees Nvidia's server GPU and software efforts, argues the company's strengths in the AI accelerator market go well beyond developing ...
As developers, where can we find software projects abroad? - Business Advice  Business.comMy question is general but where do people find new software projects from abroad like the US, UK, Canada, Australia? We are developers and we are looking ...
Pentagon promises to get to work on software acquisition overhaul  Federal News NetworkThe Pentagon's acquisition chief vowed on Thursday that the Defense Department will get to work immediately on a sweeping revamp of DoD's practices and ...
Adobe CEO Reflects on Software’s Role in Digital Transformation  SDxCentralThe ascent of cloud computing and mobility changed the fundamental structure of Adobe's business, and it came just as the recession hit.
Nvidia’s latest AI software turns rough doodles into realistic landscapes  The VergeAI is going to be huge for artists, and the latest demonstration comes from Nvidia, which has built prototype software that turns doodles into realistic landscapes.
5 Biggest Server Vendors With Nvidia's T4 GPUs And AI Software  CRNHere are five of the hottest servers in the world that will be integrated with Nvidia T4 GPUs and Nvidia Cuda-X AI acceleration software.
Baker Hill's new software fuels firm's rapid growth  Indianapolis Business JournalA year after the release of the fifth and final phase of its NextGen platform, Carmel-based financial software firm Baker Hill is experiencing significant growth.
Intain Fintech to launch software product in India  The HinduIntain Fintech to launch blockchain productIntain Fintech, an AI and block chain-based software products firm, will be launching eMulya, an intelligent block ...
Nvidia launches new hardware and software for on-prem and cloud providers  Network WorldNvidia used its GPU Technology Conference in San Jose to introduce new blade servers for on-premises use and announce new cloud AI acceleration.
Breakthrough programmable computer made from DNA running chemical software  Boing BoingFor more than two decades, researchers have explored using DNA as a chemical computer. Until now though, DNA computers have only been capable of ...
A decade on, smartphone-like software finally heads to space - Tech News  The Star OnlineOnce a traditional satellite is launched into space, its physical hardware and computer software stay mostly immutable for the rest of its existence as it orbits the ...
Simplicity, Please - A Manifesto for Software Development  InfoQ.comA headlong dash to market may lead you entirely in the wrong direction. Complexity is the greatest impediment to a software company's growth — and simplicity ...
Lawmaker Wants VA to Explain a Software Tool USDS Flagged as Flawed  NextgovA ProPublica report exposed serious issues in a Veterans Affairs Department software tool.
How can AI influence the decisions you make about your software team?  ITProPortalNew technologies such as artificial intelligence (AI) are changing the way software organisations measure development performance and allocate resources.
When Windows users switch to Macs: Essential software and handy tools  ZDNetJason Perlow is becoming a corporate Mac user. What does he need to get started?
Snag this realistic painting software on sale for 40% off  MashableThe creative prowess of a great artist is contingent upon what they do with what they have. If someone is truly talented, they can create something spectacular ...
China’s Alibaba Partners With Chinese Software Giant to Promote Blockchain Development  CointelegraphNews. Chinese e-commerce conglomerate Alibaba and Aerospace Information Co., a major software developer and provider, have signed a strategic ...
Lockheed Martin Accelerates Transition to Software-Defined Space  Via SatelliteAerospace manufacturer Lockheed Martin will integrate its new software-defined satellite architecture, SmartSat, on 10 of its nanosatellite missions this year, ...
BAE Systems wins contract to develop air mission planning software  Airforce TechnologyBAE Systems secured a contract from the US DARPA to continue the development of autonomy software to improve air mission planning for the military.
OceanLotus adopts public exploit code to abuse Microsoft Office software  ZDNetAPT32 is using a public exploit to abuse Office and compromise targeted systems.
What No-Code Software Really Looks Like  ForbesParadoxically perhaps, to really explain what no-code is and how simple it is, we need to explain the basics of declarative programming and get that ...
NODE40 beefs up cryptocurrency reporting software  Accounting TodayNODE40, a blockchain accounting software maker that provides Balance, a cryptocurrency reporting software, has created a new tier for Balance aimed at ...
Intel sent me graphics software for a discrete GPU that doesn't exist yet  PC GamerIn "moving to become a discrete graphics company," Intel has released early access software for its graphics chips and eventually dedicated GPUs.
Microsoft Preps Defender ATP Security Software for macOS  Tom's HardwareMicrosoft announced Defender ATP enterprise services for businesses that use both Windows and macOS computers.
The 6 Best Apps and Software for Recording Podcasts  MakeUseOfAnyone can create a podcast, but you've got to have the right tools. Here are the best apps and software for podcasters.
Microsoft rolls out anti-virus software to MacOS  Business StandardMicrosoft is rolling out its Windows Defender anti-virus software to Apple's operating system MacOS, with full virus and threat protection along with the usual ...
NIST to Implement New Software Security Development Guidelines  MeriTalkAt the quarterly meeting of the National Institute of Standards and Technology's (NIST) Information Security and Privacy Advisory Board, researchers said that ...
AI has become table stakes in sales, customer service and marketing software  TechCrunchArtificial intelligence and machine learning has become essential if you are selling sales, customer *service* and marketing software, especially in large ...
Detroit Downloads Tesla’s Software Strategy  The Wall Street JournalAuto makers have outfitted new cars with a lot of technology, effectively turning them into computers on wheels. Their next challenge: refreshing the software ...
10 Best Software Development Methodologies For Embracing Software Engineering Projects  Analytics India MagazineIn the current scenario, technology is evolving at a fast pace and is pushing the software companies to move and work in a fast-paced motion.
Amazon's Rekognition software lets cops track faces: Here's what you need to know  CNETAmazon wants to provide facial recognition software to law enforcement and businesses. We have questions.
How to Become a Software Engineer, 2019's Best Job  Innovation & Tech TodayThe US News and World Report placed "software engineer" at the top of the "Best Jobs" list for 2019. Here's how to capitalize on this growing industry.
February 2019 NPD: Anthem and Jump Force top software sales  VentureBeatAnthem was the top-selling game, which isn't too surprising. But Jump Force came in at No. 2, which once again shows the inexplicable power of anime.
Nokia 7 Plus units sent data to Chinese servers due to software 'error', Finland now investigating HMD  BGR IndiaWhile HMD Global has acknowledged software glitch, it said there was no personal data transfer to any third party. - Nokia 7 Plus units sent data to Chinese ...
MICROCOST or SOFTWARE: HARD COST | News  Washington Times HeraldANDERSON — Two years ago Microsoft announced it was ending support in 2020 for its computer operating system Windows 7, causing problems for ...
HSBC signs deal to use BlackRock's 'Aladdin' software worldwide  ReutersHSBC has signed a deal to offer BlackRock's Aladdin investment management software to the bank's wealthy customers, in a boost to the U.S. asset manager's ...
PlayStation software video showcase 'State of Play' set for March 25  GematsuSony Interactive Entertainment has announced “State of Play,” the first episode in a new video showcase series featuring updates and announcements from the ...
Morgan 911 studies profile software | Morgan County  The Decatur DailyMorgan County 911 is looking into implement software that will help first responders be more informed when they arrive at an emergency.
'Sekiro' Review Round Up - From Software Has Reinvented Itself Again  LADbibleThe scores are in and Sekiro looks to be a certified banger. Here's a round up of all the critics.
Amazon software engineer in second month of protests against conditions  World Socialist Web SiteOleg Churyumov, an Amazon software engineer at Amazon, has been protesting across Seattle, Washington, since February against the soul-crushing work ...
Air Force Magazine  Air Force MagazinePentagon acquisition chief Ellen Lord said work is already underway to meet one of 10 key recommendations the Defense Innovation Board issued in its ...
Oracle (ORCL) Powers Software Offerings With AI Capabilities  Zacks.comOracle (ORCL) ramps up its cloud offerings with robust ML and AI capabilities.
EC deleted voter data in Telugu states based on a software algorithm: PIL alleges  The News MinuteThe Telangana EC denied allegations that the EROs in Andhra Pradesh deleted a huge number of voters in 2015 solely based on numbers thrown up by a ...
Atlassian to Pay $165 Million for AgileCraft in Workplace Software Push  FortuneAtlassian, known for the popular Jira software, will buy AgileCraft for $165 Million as part of a push into workplace software.
Boeing expects 737 Max software fix by end of March  BBC NewsBoeing has told airlines it expects to have new software for its 737 Max plane ready by the end of the month. The plane has been grounded following the ...
AI software startup Skymind raised $11.5 million with this pitch deck  Business InsiderSkymind's software helps enterprise's AI systems tap into their stores of data.
Jet engines get planes in the sky, but software keeps them safe  Popular ScienceEven before the crash in Ethiopia, Boeing had been working on a software update.
The Software That Shapes Workers’ Lives  The New YorkerMiriam Posner writes about the “supply chain”—the vast network of factories, warehouses, and shipping conduits through which products flow—and how it ...
Security Alert: Malicious Malware Detected in Cryptocurrency And Forex Trading Software  CryptoGlobeIsrael-based fintech firms that develop cryptocurrency traQding and forex-related products have reportedly been targeted by malicious malware programs.
The Week in Tech: Our Future Robots Will Need Super-Smart Safety Checks  The New York TimesSoftware looks to be at the heart of the recent Ethiopian Airlines crash. Safety approval of such systems will only get harder as technology advances.
With great speed comes great responsibility: Software testing now a continuous race  ZDNetContinuous integration and continuous delivery is giving us software updates every day in many cases. A recent survey of 500 IT executives finds 58 percent of ...
NAB sets software bots loose on its email avalanche  iTnewsAutomatically extracting action items in 70 percent of cases.
America’s Cities Are Running on Software From the ’80s  BloombergQuint(Bloomberg Businessweek) -- The only place in San Francisco still pricing real estate like it's the 1980s is the city assessor's office. Its property tax system dates ...
Boeing 737 Max Major Design Flaws, Not a Software Failure  MishTalkThe 737 Max crashes stem from severe design issues and flagrant cost-cutting efforts, not software issues.
5 Futuristic DJ Software Features That Will Soon Be Commonplace  DJ TechtoolsWe hear a lot about “the future of DJing”, but what features are actually in the near-future of DJ softwares like Traktor, Serato, Rekordbox, and Virtual DJ?
Uber tried to undercut competition by using software to poach drivers, report claims  Daily MailAccording to a report from the Australian Broadcasting Company , the ride sharing company Uber is coming under scrutiny for deploying software that helped it ...
Rs 5kcr to put software products companies on fast lane  Economic TimesNEW DELHI: The government on Thursday approved the creation of a Rs 5,000-crore fund to back software products startups in the country as part of its broader ...
99 suppliers join DTA's govt-wide software panel - Strategy - Software  iTnewsThe government's co-ordinated procurement arrangement for software licensing and services has climbed 100-fold after the Digital Transformation Agency ...
Microsoft Office Is The Most Exploited Software By Cybercriminals  FossbytesA list of the top 10 most exploited vulnerabilities in 2018 has revealed that Microsoft Office was the favorite victim of cybercriminals. Microsoft Office ...
Apple's March Event: a big new move into subscription software  AppleInsiderIt's almost "show time." That's the phrasing used in media invitations to Apple's March 25 event, where the company is expected to unveil its subscription ...
Margaret Hamilton Led the NASA Software Team That Landed Astronauts on the Moon  Smithsonian.comApollo's successful computing software was optimized to deal with unknown problems and to interrupt one task to take on a more important one.
The security features you should expect from your work management software  TechRadarWrike CEO tells us why security should underpin all your work processes.
AT&T CFO Highlights Software Role in 5G  SDxCentralAs more markets gain 5G coverage around the country, software will lead the way, according to AT&T CFO John Stephens.
LaunchDarkly raises $44 million to help software developers test new features  VentureBeatLaunchDarkly, a startup that provides a feature flagging framework for software development, has raised $44 million in a series C round.
Apple Now Seeking More Software Engineers Than Hardware Engineers  MacRumorsSoftware engineering positions have outnumbered hardware engineering positions in Apple job listings for the first time since at least the first...
Reports: Boeing to issue software fix for 737 Max in 10 days  CNBCCNBC's Dom Chu reports on sources saying that Boeing will update the Boeing 737 Max 8's software in 10 days. The planes have been grounded in a number ...
From Hardware to Software: China's 2019 Military Budget and Priorities  The DiplomatMarch has marked the budget season for the United States and China alike. Earlier this month, at the National People's Congress, Beijing announced a 7.5 ...
Android update - This handy improvement makes Google's software even better  ExpressANDROID is set to receive a handy improvement that will make the Google software even better and here's everything new.
Advellence and Magnitude Software Partner to Deliver Intelligence-based Product Information Management  PR WebMagnitude Software teams up with Advellence to enable retailers, distributors and global brand manufacturers to drive competitive advantage through ...
Vinicius Honorio's favourite music software  MusicRadarThe Brazilian techno producer and label owner gets passionate about his five favourite software tools.
Sen. Menendez Calls for Twitter to Stop Spreading Software That Can Help Make Weapons - Hit & Run : Reason.com  ReasonSen. Bob Menendez (D-N.J.) made a direct call to Twitter chieftain Jack Dorsey asking him to eliminate tweets from a particular user, @ivanthetroll12, ...
Red Team to help secure open-source software  ZDNetThe Linux Foundation's new Red Team project will incubate open-source cybersecurity tools.
Get the software tools to become a DJ for just $49!  Android CentralDJ software can be expensive, but Android Central Digital Offers is hear to help.
How HR management software can help organisations streamline work  YourStory.comOver the past decade, HR Management Software has evolved in many ways. A new system has now taken over the conventional Human Resource ...
Boeing to upgrade software in 737 MAX 8 fleet in 'weeks'  Reuters(Reuters) - Boeing Co confirmed late on Monday it will deploy a software upgrade to the 737 MAX 8, a few hours after the Federal Aviation Administration said it ...
Eight Roads Ventures leads funding in software engagement firm Whatfix  VCCircleWhatfix, which provides solutions for engagement with software, has raised $12.5 million (Rs 87 crore at current exchange rate) in a Series B funding round led ...
Nvidia's CEO Reveals New Hardware, Software and Impressive Stats at Conference  TheStreet.comNvidia (NVDA - Get Report) CEO Jensen Huang made plenty of hardware and software announcements during a 160-minute keynote talk at the company's ...
Nine most in-demand jobs in software engineering, according to Hired  Business InsiderThese are the nine most in-demand jobs in software engineering and their average salaries in San Francisco and New York, according to Hired.
10 Productivity Tools for Software Engineers  Interesting Engineeringhere are the tools and platforms that can make you a software engineer that you have always aimed for.
Take-Two Interactive: Overvalued By More Than 15%  Seeking AlphaTTWO generates about 80% of its revenue from three games. DLC *content* is responsible for the majority of sales. Growth has mostly been inorganic, which has ...
Smartsheet Emerging As A Leader In Collaboration Software  ForbesOrganizations can empower their employees to work more efficiently and effectively by promoting increased teamwork. The latest outlook from Smartsheet ...
Backdoored GitHub accounts spewed secret sneakerbot software  Naked SecurityResearchers have uncovered a network of GitHub accounts containing backdoored versions of legitimate software. In some cases, the doctored applications ...
Dash Releases Software to Improve Decentralization  CoingapeIn a drive to implement complete decentralization in the Dash Autonomous Organization, Nathan Marley, Dash Core Deputy CTO has developed the software ...
FairCom and Software AG sign new contract for c-treeACE Database  PRNewswireMILAN, March 22, 2019 /PRNewswire/ -- FairCom Corporation, one of the world's most trusted names in database technology, announced today the extension of ...
Two Seattle cannabis software companies merging to build bigger stake in a growing market  GeekWireDauntless, Inc., a Seattle-area software developer providing point-of-sale and tracking software to the cannabis industry, has acquired pot sales software ...
Synthesis-searching software's superior scoring sharpens selections | Research  Chemistry WorldThe developers of Chematica, a computer program that can predict organic synthesis routes, have significantly improved the way it chooses from the options it ...
Boeing to Update Planes' Software After Two Deadly Crashes  MotherboardBoeing plans to deploy a software update for its 737 Max plane “designed to make an already safe aircraft even safer,” the company said in a statement two days ...
Boeing Plans to Fix the 737 MAX Jet With a Software Update  WIREDThe investigation into the crash of an Ethiopian Airlines 737 MAX 8, which killed 157 people on Sunday, is still in its earliest stages, but already regulators ...
100 software jobs to be filled at Indianapolis-based Kerauno  WRTV IndianapolisHiring Hoosiers is a new initiative from RTV6 that works to connect Hoosiers to employment opportunities, career development resources, training programs and ...
Round Up: Sekiro: Shadows Die Twice PS4 Reviews - Another From Software Classic?  Push SquareWhile Sekiro certainly shares DNA with the previous Soulsborne games, fundamental sword-fighting battle mechanic changes leave it feeling *fresh*. However, as ...
WSJ: Fix to Boeing 737 Max 8 planes delayed in part by government shutdown  CNNWashington (CNN) US officials say the recent government shutdown played a part in the delay of Boeing's software update for its 737 Max aircraft, which has ...
Astronomy Software by Any Other Name  Linux JournalIn this article, I introduce another option available for the astronomers out there—specifically, Cartes du Ciel, also known as SkyChart. Similar to other larger ...
Google: Software is never going to be able to fix Spectre-type bugs  Ars TechnicaResearchers also devise a Spectre-like attack with no known mitigation.

Microsoft Great Plains e-Commerce ? additional considerations for programmer

Microsoft Great Plains, designed back in 1990th as database transferable... Read More

Putting Screensavers Under Control

No matter how much you enjoy your favorite screensavers, sometimes... Read More

Linux for Home Users

Hey Guys! Don't raise your eyebrows or fear by hearing... Read More

Microsoft Blues

With the advent of 'Service Pack 2' for Windows XP... Read More

Making The Decision To Automate Your Software Testing

Not every software testing project can or should be automated.... Read More

A Time-Saving Programming Tactic that Doesn?t Work

Let's say that you have a software project that's under... Read More

Microsoft Great Plains Integration Manager ? Advanced Techniques

Great Plains Integration Manager scripting and translation - overview for... Read More

Screenshots Vista Windows

Features Additionally, Vista will include many other new features.Aero Vista... Read More

Microsoft Great Plains Inventory Control ? Overview For Consultant

Microsoft Business Solutions Great Plains is marketed for mid-size companies... Read More

Brand Your Websites URL With a Favicon

Have you ever noticed that when you look at your... Read More

Microsoft Great Plains Integration Manager ? Working With Text File

Microsoft Business Solutions main middle market ERP application - Microsoft... Read More

Navision Customization: C/SIDE, C/ODBC, C/FRONT, XBRL ? Development Options

Microsoft bought Navision, Denmark based software development company, along with... Read More

Introduction To ISDN, Part III: PAP

Introduction To ISDN, Part III: Configuring PPP PAP AuthenticationNow we... Read More

Groupware Finds Home in American Business: Collaboration Tool Analysis

What is Groupware?Have you ever had to manage document collaboration... Read More

Fleet Maintenance Software Reviews

Innovative Maintenance Systems (IMS) is one company that offers solutions... Read More

Cisco Certification: Introduction To ISDN, Part IV

In part III of this ISDN primer, we learned that... Read More

Microsoft Great Plains Customization and Development ? Overview for Programmer

When Great Plains Software was designing and developing Great Plains... Read More

Microsoft Great Plains Logistics & Warehouse Management ? Implementation & Customization Highlights

Logistics automation is often considered as barcoding extension to Sales... Read More

ERP for Large Corporation ? New Selling Strategy

Our opinion is based on our Microsoft Business Solutions Great... Read More

DVD Burning Tips

CD and DVD replication is a process that works by... Read More

Microsoft Great Plains Accounting/ERP Implementation ? Finance Industry Customization Example

Microsoft Business Solutions Great Plains is very generic accounting application... Read More

Easy Guide to RAID Recovery

What is RAID RECOVERY?RAID stands for Redundant Array of Inexpensive... Read More

5 Time-Saving Tips in Microsoft Word

Whether you have used Microsoft Word for years, have just... Read More

Microsoft Great Plains Upgrade ? Things to Consider and FAQ

If you have Microsoft Great Plains and support it for... Read More

Business Plan Software Review: Ultimate Business Planner?

One of the main reasons business owners and entrepreneurs use... Read More