C + + Supplements--function templates
Preface
The core idea of generics is the separation of data and algorithms. Function templates are the basis of generic programming.
function Templates
The function template begins with template<arg_list> and Arg_list is a list of generic parameters.
1. Determining the number of generic parameters for a templateinstance One
Here is an addition function template that, when instantiated, we pass in the normal 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, N) << endl;cout << Add (12.3) << endl;cin.get (); return 0;}
Run
Example Two
We can also pass in 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 Calculator
2. Non-deterministic number of generic parameters for a template
#include <iostream> #include <cstdarg>using namespace std;//The function of this null parameter is used to recursively terminate void show () {}//parameter number is variable, Parameter types are also diverse template<typename T, TypeName ... Args> //typename ... Args is a mutable type list void Show (T T, Args...args) {cout << t << ends;show (Args ...);} int main () {Show (1, 2, 3, 4); Show (' A ', ' B ', ' C ', ' d '); Cin.get (); return 0;}
Run
Directory of all content
C + + Supplements--function templates