Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the function templates in C++

2025-01-16 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What this article shares with you is about what function templates there are in C++. The editor thinks it is quite practical, so I share it with you to learn. I hope you can get something after reading this article. Without saying much, follow the editor to have a look.

Templates are templates, but unlike familiar models, templates are used to generate different things (functions or classes). There are function templates and class templates in C++. Today we're going to talk about function templates.

Scenario: if we need a function to add or we need to implement the print function ourselves, how do we deal with the different incoming parameters (double? Int? Char? Short? What about string?)?

You may blurt out "function overloading", but that means you have to write at least two or more functions to support changes in your parameter type and number, right? And this approach does not support expansion, if there are other requirements, it is necessary to add overloaded functions, which is stupid, I believe you also think so. So what's a better way? Function template.

Let's look at examples.

1 template / / first declare the template parameter T2 typename T add (const T & num1, const T & num2) / / define the template function. Note that the parameter type 3 {4 return num1 + num2; 5} 6 7 int main () 8 {9 cout

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report