[C + +] use Xcode to write C + + program [5] function overload and template

Source: Internet
Author: User

Using Xcode to write the overloads and templates of C + + program [5] Functions

This section includes function overloading, implicit function overloading, function templates, parametric function templates

Overloading of functions

#include <iostream>using namespacestd;intOperate (intAintb) {returnAb);}DoubleOperate (DoubleADoubleb) {returnAb);}intMain () {intx =5; inty =2; Doublen =5.0 ; Doublem =2.0; cout<< operate (x, y) <<'\ n'; cout<< operate (n,m) <<'\ n'; return 0;}

Print results

Ten 2.5  0

function templates

#include <iostream>using namespacestd;//TemplatesTemplate <classT>t sum (t A, T b) {T result; Result= A +b; returnresult;}intMain () {//Value Initialization    inti =5; intj =6; intK =0; Doublef =2.0, G =0.5, H; //using Template FunctionsK = sum<int>(i, j); H= sum<Double>(f, g); //Print Outputcout << k <<'\ n'; cout<< h <<'\ n'; return 0;}

Print results

 - 2.5  0

Template Auto-match

#include <iostream>using namespacestd;template<classTclassU>BOOLare_equal (T A, U b) {return(A = =b);}intMain () {//Automatic template recognition    if(Are_equal (Ten,10.0)) cout<<"x and Y are equal\n"; Elsecout<<"x and y is not equal\n"; return 0;}

Print results

0

Template with Parameters

#include <iostream>using namespacestd;template<classTintN>T fixed_multiply (t val) {returnVal *N;}intMain () {std::cout<< fixed_multiply<int,2> (Ten) <<'\ n'; Std::cout<< fixed_multiply<int,3> (Ten) <<'\ n';}

Print results

 -  -  0

[C + +] use Xcode to write C + + program [5] function overload and template

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.