Template is an example of Objective C ++.

Source: Internet
Author: User

When using the template, remember that typename and class are used as parameters. It's amazing to see it again.

Template parameters are not limited to types. You can use built-in types in the compiler.

The template tells the compiler that some definitions contain one or more unknown quantities (constants or types ).CodeThe compiler must replace these values.

TMP's "Hello World"ProgramCalculate a factorial during compilation. It is not an exciting program. However, even if it is not "Hello World", it also helps to get started with the language. TMP factorial calculation demonstrates a loop through recursive template instantiation (recursive template instantiation. It also demonstrates a way to create and use variables in TMP. See:

Template <unsigned n> // general case: the value
Struct factorial // factorial <n> is n times the value

{// Of factorial <n-1>

Enum {value = N * factorial <n-1 >:: value };

};

Template <> // special case: the value
Struct factorial <0 >{// factorial <0> is 1
Enum {value = 1 };

};

This template metaprogram (template metaprogram) (actually only a separate template metafunction (template mettorial) factorial) is provided. You can obtain factorial (n) by referencing factorial <n >:: value).

The cyclic part of the code appears in template instantiation (template instantiation) factorial <n> references template instantiation (template instantiation) factorial <n-1>, in this way, it will continuously instance new types of factorial <n-1> and obtain the value values of each type to multiply. Because it is an Enum constant, therefore, the value of each value is calculated during compilation.

All correct recursion (recursion) has an exit. Here, it is template specialization (template-specific) factorial <0>.

Each instantiation (Instance) of the factorial template is a struct, and each struct has a corresponding factorial value.

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.