C + + templates (template) are the basis of generic programming (generic programming);
Object-oriented programming is known as type (type) when running (run time); Generic programming is compiler (compilation) knows the type;
Functions template (function template) contains a list of template parameters (template parameter list);
Each parameter type must precede the keyword TypeName or class, use TypeName as much as possible, and express the meaning more clearly;
Non-type template parameters (Nontype Template Parameters) can only be integer types, pointers, references;
The integral type must be a constant expression (constant expression), and the pointer and reference must point to a static type;
Template functions need to guarantee the type of function independent (type independence) and portability (portability); Use STL library function as far as possible;
Code:
* * * cppprimer.cpp * * Created on:2013.11.21 * author:caroline//*eclipse CDT, gcc 4.8.1*/ #include <iostream> #include <vector> #include <functional>//less<> #include <cstrin g>//strcmp template <typename t> int compare (const t &V1, const T &v2) {if (Std::le Ss<t> () (v1, v2)) return-1;
Using a library function instead of "<" avoids pointer address comparisons if (std::less<t> () (v2, v1)) return 1;
return 0;
} template<unsigned N, unsigned m> int compare (const char (&P1) [N], const char (&P2) [M]) { Std::cout << "n =" << N << "m =" << m << Std::endl; Add a null terminator (null terminator) return std::strcmp (P1, p2);
Compare only the first character} int main (void) {std::cout << compare (1, 0) << Std::endl;
Std::vector<int> V1{1, 2, 3}, V2{4, 5, 6}; Std::cout << Compare (v1, v2) << Std::endl;
Std::cout << Compare ("Girl", "lad") << Std::endl;
int a[] = {1, 2, 3, 4}, b[] = {1, 3, 4, 5};
Std::cout << Compare (A, b) << Std::endl;
return 0; }
Author: csdn Blog spike_king
More Wonderful content: http://www.bianceng.cnhttp://www.bianceng.cn/Programming/cplus/