Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

What are the function templates in C++

Shulou Source: shulou.com Published: 2022-06-02 08:04:56 09月23日 Update

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

Tags: Templates parameters functions types special cases specializations instances compilers that is compilers inferences examples ranges parts work generation so that Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Linux MariaDB vpn Shulou Information Docker