C + + Templates learning process One

Source: Internet
Author: User

I. Defining the MAX function template

// basics/mas.hpptemeplate<typename t>constConst const &   b) {    return a < b? b:a;}

Declaration of template Parameters

Template <comma-separated-list-of-paramaters>//temeplate< parameter list, separated by commas >

Another equivalent definition of template max ()

Temeplate <class t>const-Const const &  B)    { return a < b? b:a;}

Using templates

//Basics/max.cpp#include <iostream>#include<string>#include"max.hpp"intMain () {inti = the; Std::cout<<"Max (7,i):"<<::max (7, i) <<Std::endl; DoubleF1 =3.4; DoubleF2 =-6.7; Std::cout<<"Max (F1,F2):"<<::max (f1, F2) <<Std::endl; strings1="mathmatics"; stringS2="Math"; Std::cout<<"Max (S1,S2):"<<::max (S1, S2) <<Std::endl; }

The max () template is preceded by a domain qualifier::, to confirm that Max () is called in the global namespace.

Replacing a template parameter with a specific type is called instantiation. It produces an instance of a template, namely:

The first invocation of Max () instantiates the max template for int, just as with a separate declaration and implementation as follows

Const int int Const int const&);

C + + Templates learning process One

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.