C + + Programming Method 4: Function templates

Source: Internet
Author: User

function templates

Some algorithms are independent of type, so you can define a function's parameter type as a special "parameter" so that you get a "function template"

How to define a function template:
Template<typename t> return type function name (function parameter);

such as: Template<typename t> t sum (t A, T B) {return a + B;}

The function template calls, because the compiler can automatically deduce the actual parameters of the type, so formally call a function template and

There is no difference between ordinary functions, such as:

int main ()

{

int a = 3, b = 4;

cout << sum (A, b);

float f1=1.3, f2 = 9.1;

cout << sum (F1,F2);

}

Function template parameters can also be assigned default values, such as

Template<typename T0 = float,

TypeName T1,

TypeName T2 = float,

TypeName T3,

TypeName T4>

Tofunc (T1 v1,t2 v2, T3 v3, T4 v4) {...}

...

Func (n/a);

Func (' A ', ' B ', ' abc ');

C + + Programming Method 4: Function templates

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.