Function Templates Functions and classes help to make programs easier to write, safer, and more maintainable. However, while functions and classes do have all of those advantages, in certain cases they can also be somewhat limited by C++'s requirement that you specify types for all of your parameters. For example, you might want to write a function that calculates the sum of two numbers, similar to this:
int sum(int a, int b) {
return a+b;
}
Function Templates
We can now call the function for two integers in our main.
int sum(int a, int b) {
return a+b;
}
int main () {
int x=7, y=15;
cout << sum(x, y) << endl;
}
// Outputs 22
Function Templates
It becomes necessary to write a new function for each new type, such as doubles.
double sum(double a, double b) {
return a+b;
}
Wouldn't it be much more efficient to be able to write one version of sum() to work with parameters of any type?
Function templates give us the ability to do that!
With function templates, the basic idea is to avoid the necessity of specifying an exact type for each variable. Instead, C++ provides us with the capability of defining functions using placeholder types, called template type parameters.
To define a function template, use the keyword template, followed by the template type definition:
template
Function Templates
Template functions can save a lot of time, because they are written only once, and work with different types.
Template functions reduce code maintenance, because duplicate code is reduced significantly.
Function Templates
In our main, we can use the function for different data types:
template <class T, class U>
T smaller(T a, U b) {
return (a < b ? a : b);
}
int main () {
int x=72;
double y=15.34;
cout << smaller(x, y) << endl;
}
// Outputs 15
Function Templates
T is short for Type, and is a widely used name for type parameters.
It's not necessary to use T, however; you can declare your type parameters using any identifiers that work for you. The only terms you need to avoid are C++ keywords.
还有两章就要撒花完结 拿到证书了 历经一年 哈哈哈 拖的太久了 ✿✿ヽ(°▽°)ノ✿