C ++ collection-function templates, collection-function templates
C ++ collection-function Template
Preface
The core idea of generics is data and algorithm separation. Function templates are the basis of generic programming.
Function Template
The function template starts with template <arg_list>. arg_list is a list of generic parameters.
1. determine the number of generic parameters of the template instance 1
The following is an addition function template. During instantiation, we pass in a common data type.
#include <iostream>using namespace std;template<typename T1, typename T2>auto add(T1 t1, T2 t2)->decltype(t1 + t2){return t1 + t2;}int main(){cout << add(12.3, 12) << endl;cout << add(12, 12.3) << endl;cin.get();return 0;}Run
Instance 2
You can also input the function type.
#include <iostream>using namespace std;template<typename T, typename F>void exec(const T &t, F f){f(t);}int main(){exec("calc", system);cin.get();return 0;}Run system ("calc"); open the Calculator
2. The number of template generic parameters is unknown.
# Include <iostream> # include <cstdarg> using namespace std; // the function of this null parameter is used to recursively terminate void show () {}// variable number of parameters, parameter types are also diverse. template <typename T, typename... args> // typename... args is a variable type list void show (T t, Args... args) {cout <t <ends; show (args ...);} int main () {show (1, 2, 3, 4); cout <endl; show ('A', 'B', 'C', 'D '); cin. get (); return 0 ;}Run
The following uses the function template to simulate the printf () function.
# Include <iostream> # include <cstdarg> using namespace std; void PRINTF (const char * format) {cout <format ;}template <typename T, typename... args> void PRINTF (const char * format, T t, Args... args) {if (! Format | * format = '\ 0') return; if (* format =' % ') // processing format prompt {format ++; char c = * format; if (c = 'D' | c = 'F' | c = 'C' | c = 'G ') // For the moment, we only process these types of data. For other cases, {cout <t; format ++; PRINTF (format, args ...);} else if (c = '%') {cout <'%'; format ++; PRINTF (format, t, args ...);} else {cout <* format; format ++; PRINTF (format, t, args ...);}} else {cout <* format; PRINTF (++ format, t, args ...);}} int main () {PRINTF ("% asdljl % 5234la; jdfl; \ n"); PRINTF ("% d alsd, % fasdf .. % g .. % c \ n ", 12, 3.4, 5.897, 'A'); cin. get (); return 0 ;}Run
Simple simulation of printf () code download using function templates
Directory of all contents