C++11 tuple& Variable parameter template
1 Template2 3 voidPrint (T value)4 5 {6 7Std::cout << Value <<Std::endl;8 9 }Ten One Template A - voidPrint (head Head, Rail ... Rail) - the { - -Std::cout << Head <<", "; - + Print (rail ...); - + } A at intMainintARGC, _tchar*argv[]) - - { - -Print (1); - inPrint ("Hello",1); - toPrint (1,"Hello"); + -Print (1,"Hello",'H'); the * GetChar (); $ Panax Notoginseng return 0; - the}
View Code
In the above code, we first define a function template with only one template parameter, which simply outputs the value of the parameter passed in. A function template with a mutable parameter is then defined, which outputs the value of the first parameter and then recursively calls itself. Attention Rail ... This notation, which means that the function parameter packet is split into one parameter and passed into print. In this way, the first parameter in the function parameter package is passed to the head, and the remaining parameters are re-formed into a function parameter package passed to rail. When a recursive call to a function parameter package has only one parameter, the print function that has only one template parameter is called.
After understanding how variable template parameters are used, let's write one of our own printf functions.
1 voidMyprint (Const Char*pszText)2 3 {4 5ASSERT (PszText! =nullptr);6 7Std::cout <<PszText;8 9 }Ten One Template A - voidMyprint (Const Char*PszText, T value, args ... args) - the { - -ASSERT (PszText! =nullptr); - + while(*pszText) - + { A at if(*psztext = ='%'&& *++psztext! ='%') - - { - -Std::cout <<value; - inMyprint (+ +)PszText, args ...); - to return; + - } the *Std::cout << *psztext++; $ Panax Notoginseng } - the } + A int_tmain (intARGC, _tchar*argv[]) the + { - $ Myprint (nullptr); $ -Myprint ("Hello"); - the GetChar (); - Wuyi return 0; the -}
View CodeThe implementation of the above code for the application of variable-parameter template, of course, is not as robust as the printf function, myprint to identify the format parameter is%+ next character, such asIf the condition is satisfied, the first parameter after the parameter package is split from the args parameter
C + + variable parameter template implementation output