Some advanced uses of C + + template (meta-code, Variadic, functor, using use method)

Source: Internet
Author: User
Tags aliases variadic

1. General function Variable parameter template

For some time, we can not know exactly, when the number of parameters of the function, but do not want to use too much so-called function overloading, then you could emulate the following example:

1#include <iostream>2#include <Array>3 voidShowAll () {return; }4 5Template <typename R1, TypeName ... Args>6 7 voidShowAll (R1var, Args...args) {8 9Std::cout <<var<<Std::endl;Ten showall (args ...); One } A  - intMainintargcChar*args[]) { -  the      -ShowAll (1,2,3,4,5); -ShowAll ("Gxjun","DADW","Dasds"); -ShowAll (1.0,2.0,3.5); +Std::cin.Get(); -     return 0; +}

In game development, the template is often used, the type is not sure, the number of parameters is not deterministic, so you need to use a similar recursive function to deal with. The first function, which represents the end of the argument, is 0 o'clock.

Effect:

2. How to use an imitation function:

The first is the definition of the functor: The functor is also called a Function object (functional object, or Functor), which is defined as any object that can be called as a function. A normal function is a function object, and a function pointer is, of course, the generalized definition of any class object that defines operator () can be considered a function object. (Documents found)

In fact, to be straightforward, it is an object (struct or class) that is not a function but has functions and uses the same function.

Here's a chestnut (function function with structure):

1 /*about C + + profiling functions*/2#include <iostream>3#include <functional>4 using namespacestd;5 using namespacestd::p laceholders; 6 7Template <typename R1, TypeName r2>8 structCalc9 {Ten     voidAdd (R1 a) { Onecout << a <<Endl; A     }; -     voidAdd_1 (R1 A, R1 b) { -cout << A + b <<Endl; the     }   - }; -  - intMainintargcChar*args[]) { +  -     //function Pointers +     void(calc<int,Double::* FC) (inta) = &Calc<int,Double>:: add; A     //FC (+); at     //Obviously, the above-mentioned equation is more troublesome. -      -Calc <int,int>Calc; -Auto fun = bind (&Calc<int,int>::add, &Calc, _1); -Auto Fun_2 = bind (&Calc<int,int>::add_1, &Calc, _1,_2); -Fun123); inFun_2 ( A, -); -Cin.Get(); to  return 0; +}

For bind () This function, the beginning is the address, the function name, followed by the first sake args .... Indeterminate parameter types,

For:

3. Using a using alias, a function pointer, typdef to implement a function call

Although it is a few lines of code, but the function in the actual application, but will play a big role.

1 //using aliases usage2#include <iostream>3#include <windows.h>4 intCalc () {5   //returns a value of 0 when no parameter is required6     return 0;7 }8 9Template <typename R1, TypeName ... Args>Ten intCalc (R1 A, Args...args) { One  A     returnA +Calc (args ...); - } -  the intMainintARGC,Char*args []) { -  -     //using function Pointers -     int(*fun) (int,int,int,int) =Calc; +System"Echo uses function pointers for 1~4 accumulation"); -Std::cout << Fun (1,2,3,4) <<Std::endl; +    //use typedef to implement this function ASystem"Echo uses typedef to achieve 1~4 accumulation"); attypedefint(*add) (int,int,int); -Add Gadd =Calc; -Std::cout << Gadd (1,2,3) <<Std::endl; -     //using a using alias to implement this function -System"Echo uses using to implement 1~4 accumulation"); -     usingFunc =int(*) (int,int,int,int); inFunc func =Calc; -Std::cout << func (1,2,3,4) <<Std::endl; toStd::cin.Get(); +  return 0; -}

4. C + + template meta-programming:

For template meta-programming: My understanding is that you want to calculate, in the compile time, has been processed to play, only need to run when the output results can!

When we often learn template meta-programming, there will be a confusing vocabulary appear, clatter, see------functional programming. What is functional programming anyway?

It is recommended to read this article, http://www.ruanyifeng.com/blog/2012/04/functional_programming.html template meta-programming uses a wide range of

We know that in the case of hardware constraints, in addition to the optimization algorithm, there is also a way to use template meta-programming. Now let's take a look at the application of the Golden Code!

The calculation of the Fibonacci sequence ...

1#include <iostream>2#include <time.h>3#include <windows.h>4 /*5 Fibonacci Sequence6 H (1) =h (0) =1;7 h (N) = h (N-1) +h (N-2);8 */9 using namespacestd;Ten  One  /*General Edition normal edition*/ A  using_int =Long;//using aliases -   - _int Feibona (_int ac) { the     if(AC = =0|| ac==1)return 1; -     returnFeibona (ac-1) +feibona (ac-2); - } -  +  /*use meta-programming to fully special version of the method as follows*/ -Template <_int n> +  structData { A      //Take enumeration at      enum{res = data<n-1>::res + Data<n-2>:: res}; -  }; -  -Template <> - structdata<1> { -     //Take enumeration in     enum{res =1L }; - }; to  +Template <> - structdata<0> { the     //Take enumeration *     enum{res =1L }; $ };Panax Notoginseng  -  the intMainintargcChar*args[]) { +  A time_t A, b; theA = clock ();//Start recording Time +cout << data<45L>::res <<Endl; -b = Clock ();//Start recording Time $System"the time spent by ECHO in meta-programming"); $cout << (Double) (B-A)/clk_tck<<"Ms"<<Endl; -A =clock (); -cout << Feibona (45L) <<Endl; theb =clock (); -System"Echo's time spent using a common algorithm");Wuyicout << (Double) (b-a)/Clk_tck <<"Ms"<<Endl; theCin.Get(); -     return 0; Wu}

The two are compared:

Some advanced uses of C + + template (meta-code, Variadic, functor, using use method)

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.