zoukankan      html  css  js  c++  java
  • 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.

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

  • 相关阅读:
    7-5 幸运彩票 (15分)
    基于Python实现学生管理系统
    NB-IoT模块烧写详细过程
    IAR软件使用的快捷键配置以及配置cc2530环境
    7-54 求方程的解 (10 分)
    7-52 计算球体积 (10 分)
    7-51 号码牌的制作 (10 分)
    7-48 输出星期名缩写 (70 分)
    7-49 求前n项的阶乘之和 (15 分)
    7-46 jmu-python-求单词长度 (10 分)
  • 原文地址:https://www.cnblogs.com/whatiwhere/p/8800259.html
Copyright © 2011-2022 走看看