C + + function template One (function template definition)

Source: Internet
Author: User

//function Template definition--data type do parameters#include <iostream>using namespacestd;/*function Template Declaration 1. A function template definition consists of a template description and a function definition, and a template description corresponds to a function definition 2. The generic parameter of the template description must appear at least once in the function definition of 3. A generic type parameter can be used in the function parameter table, You can also use generic type parameters*//*The template keyword tells the C + + compiler to do generic programming now TypeName or class tells the C + + compiler that T is a data type, do not check syntax TypeName and class can replace each other completely */Template<typename t>//can also be written template<class t>voidMyswap (t &a, T &b) {T C=A; A=b; b=c;};//void Print (T &a,t &b) {//cout << "a=" << a << "\nb=" << b << Endl;//}//Error: A template description can only correspond to a function definition, want to define a function again, you must write a template declarationTemplate<classT>voidPrint (t &a, T &b) {cout<<"a="<< a <<"\nb="<< b <<Endl;}//Multi-parameter function templatesTemplate<typename T1,typename t2>//This definition will be error mysort (a) when calling the function;//the generic parameter of the template description must appear at least once in the function definitionvoidMysort (T1 a) {cout<<"AAA"<<Endl;} Template<typename t>voidGetnum (T A,intb) {cout<<"a="<< a <<"; \nb="<<b <<Endl;}voidMain () {intA=1; intb =2; //How to use generic programming functions 1---automatic type deductionMyswap (A, b);    Print (A, b); //How to use generic programming functions 2---Explicit concrete type invocationmyswap<int>(A, b);    Print (A, b); //Mysort (a); Error: Error C2783: "Void Mysort (T1)": Failed to derive template parameters for "T2"cout <<"----------------"<<Endl; Getnum (A,4); System ("Pause");}

C + + function template One (function template definition)

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.