sololearn的c++学习记录_4m11d

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.

还有两章就要撒花完结 拿到证书了 历经一年 哈哈哈 拖的太久了 ✿✿ヽ(°▽°)ノ✿

转载于:https://www.cnblogs.com/whatiwhere/p/8800259.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值