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.

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

  • 相关阅读:
    java面试-Java内存模型(JMM)
    github常用操作
    java面试-生产环境服务器变慢,谈谈你的诊断思路
    java面试-JVM调优和参数配置,如何查看JVM系统参数默认值
    java面试-死锁产生、定位分析和修复
    Scalable IO in Java【java高效IO】
    java面试-JDK自带的JVM 监控和性能分析工具用过哪些?
    Docker简介
    使用docker部署项目
    公司系统遇到的问题,虽然解决了,但是,不知道原因。贴下图片,供下次参考
  • 原文地址:https://www.cnblogs.com/whatiwhere/p/8800259.html
Copyright © 2011-2022 走看看