C + + template meta-programming

Source: Internet
Author: User
Tags traits

Introduction:

A template is a magical thing. Many of the code that involves a template is generated by the compiler during the compilation phase.

In addition to code generation, the compiler also makes some calculations when working with templates.

Using this feature of the template, we can let the compiler do some math operations.

For example, let the compiler calculate the factorial instead of calculating the factorial when the program is running:

Below, the Fibonacci sequence is computed at compile time using a template

Introduce an example:

//Main templatetemplate<intN>structfib{enum{Result = fib<n-1>::result + fib<n-2>:: Result};};//fully-Customized versionTemplate <>structfib<1>{    enum{Result =1 };};//fully-Customized versionTemplate <>structfib<0>{    enum{Result =0 };};intMain () {inti = fib<Ten>:: Result; //std::cout << i << Std::endl;}

Thus, during compilation, a direct calculation is obtained

Fib<10>:: Value of result, then assign to I

Use

The-frepo-fdump-tree-original parameter is compiled.

Get the file:


Where the contents of the. rpo file are
M instantiationfunction.CPPD e:\ Fast plate \code\cpp\devcpp\instantiationfunctiona'- D' '__debug__' '- C' '- o' 'INSTANTIATIONFUNCTION.O' '- I.' 'D:/program Files (x86)/dev-cpp/mingw32/include' '- I.' 'D:/program Files (x86)/dev-cpp/mingw32/mingw32/include' '- I.' 'D:/program Files (x86)/dev-cpp/mingw32/lib/gcc/mingw32/4.8.1/include' '- I.' 'D:/program Files (x86)/dev-cpp/mingw32/lib/gcc/mingw32/4.8.1/include/c++' '-og' '-g3' '-fverbose-asm' '-frepo' '-fdump-tree-original' '-SHARED-LIBGCC' '-mtune=generic' '-march=pentiumpro' '-frandom-seed=0'

The. Original content is

int Main () (null-tree-original{  int);   <<cleanup_point   int;>>0;

As you can see, the compiler does not retain the contents of the fib<> , but directly computes the fib<10>::result; and assigns the value to int i.

Think this process is a bit like "C + + constant Folding" (http://www.cnblogs.com/wuqi/p/4573028.html)


(The following basic theoretical exposition, organized from http://www.cnblogs.com/salomon/archive/2012/06/04/2534787.html)

Main ideas

Using the template special mechanism to implement the compile-time conditional selection structure, the recursive template is used to realize the compile-time loop structure, and the template meta-Program is interpreted by the compiler at compile time.

Pros and cons and applicable situation

By moving the calculation from the runtime to the compile time, do as much work as possible before the result program starts, and eventually get faster programs. This means that the advantages of template meta-programming are:

1. At the cost of compile time for excellent run-time performance (typically used for performance-intensive numerical calculations in exchange for higher performance). In general, the number of times a meaningful program runs (or service time) is always much more than the number of compilations (or compile time).

2. Provide compile-time type calculation, usually this is the place where template meta-programming shines brilliantly.

Template meta-programming technology is not always an advantage:

1. Code readability is poor, and describing the algorithm in a class template may be a bit abstract.

2. Debugging difficulties, the meta-Program is executed at compile time, there is no debugger for single-step tracking meta-Program execution (to set breakpoints, view data, etc.). The programmer can only do is wait for the compilation process to fail, and then manually decipher the compiler pouring to the screen error message.

3. The compilation time is long, the program that usually has the template meta-Program produces the code size is bigger than the ordinary program,

4. Portability is poor, and the different compilers have different degrees of support for the advanced template features used for template metaprogramming.

Summarize:

Template meta-programming technology does not apply to ordinary programmers ' everyday applications, it often serves as a technical support for class library development, and performs better performance or compile-time type calculations for key algorithms of the kernel of regular template code. Template meta-programs should almost always be used in conjunction with regular code to be encapsulated inside a library. It should be transparent to the user of the library.

Engineering Application Examples

1. blitz++: Because the template meta-programming is first discovered because of numerical computation, so the early research work mainly concentrates on the numerical computation aspect, the blitz++ library uses the template to transfer the running period computation to the compile time library, mainly provides the linear algebra computation which the vector, the matrix and so on processing.

2.Loki: The power of template metaprogramming in type computing is applied to design pattern areas, and meta-programming (and some other important design techniques) is used to implement generic versions of some common design patterns. The abstract factory generic schema in the Loki library reduces the static dependency on the type without loss of type security by means of this mechanism.

3.Boost: The meta-programming library currently contains libraries such as MPL, Type traits, and static assert. The Static assert and type traits are used as the basis for the MPL. The Boost type Traits library contains a series of traits classes for extracting C + + type features. Some conversion traits are also included (such as removing a const modifier of a type). The Boost Static assert library is used for compile-time assertions, and if the evaluated expression evaluates to true at compile-time, the code can be compiled or the error is compiled.

Technical details

Template metaprogramming uses static C + + language components, which are similar to functional programming, where the main operations are integer (including Boolean, character, Integer) constants and types, and variables, assignment statements, and iteration structures are not allowed. The manipulated entity is also known as metadata (Metadata), and all metadata can be used as template parameters.

Since variables cannot be used in template metaprogramming, we can only use typedef names and integer constants. They are initialized with one type and integer value, and no new type or value can be assigned. If you need a new type or value, you must introduce a new typedef name or constant.



Other examples
//DECLARE onlystructNil;//Main templateTemplate <typename t>structispointer{enum{Result =false }; typedef Nil ValueType;};//Local specificityTemplate <typename t>structIspointer<t*>{    enum{Result =true }; typedef T ValueType;};//ExampleintMain () {cout<< ispointer<int*>::result <<Endl; cout<< ispointer<int>::result <<Endl; Ispointer<int*>::valuetype i =1; //Ispointer<int>::valuetype j = 1; //error: Using undefined type nil}

//Main templatetemplate<BOOL>structStaticassert;//Fully SpecialTemplate<>structstaticassert<true>{};//Auxiliary Macros#defineStatic_assert (exp) \{Staticassert< (exp)! =0) >staticassertfailed;}intMain () {Static_assert (0>1);}



C + + template meta-programming

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.