C + + function templates 1

Source: Internet
Author: User

1 Definition:

function templates only apply to cases where the number of parameters is the same but the type is different and the function body is the same

2 This example does not use a template case

#include <iostream>using namespacestd;voidSwap (int&a,int&b) {    intt =A; A=b; b=t;}voidSwap (Double&a,Double&b) {    Doublet =A; A=b; b=t;}intmain1 () {//long a = 2; //long B = 3; //Swap (A, b);    intA =2; intb =3; Swap (A, b);//but not a double. Introducing templates for general purposecout << a << b <<Endl; Cin.Get(); return 1;}

3 after using the template

1#include <iostream>2#include <string>3 using namespacestd;4 5 /*6 function templates apply only to the same number of parameters but differ in type and function7 in the same situation, otherwise it may not8 */9Template <typename t>//Here typename can be changed to classTen voidSwap (t &a, T &b) One { AT t =A; -A =b; -b =T; the } -  - intmain2 () - { +     intA =Ten; -     intb = -; + Swap (A, b); Acout << a << b <<Endl; at  -     Longc =Ten; -     LongD = -; - Swap (c, D); -cout << C << D <<Endl; -  in     stringSA ="Hello"; -     stringSB ="Zzong"; to Swap (SA, SB); +cout << sa << SB <<Endl; -      theCin.Get(); *     return 1; $}

----------------------->

C + + function templates 1

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.