C + + template practice

An example of the first function template 1 code #include <iostream> using namespace std; template <class T> T GetMax(T a, T b) { T resul...

An example of the first function template

1 code

#include <iostream> using namespace std; template <class T> T GetMax(T a, T b) { T result; result = (a > b) ? a : b; return (result); } int main() { int i = 5, j = 6, k; long l = 10, m = 5, n; // Because i and j are of type int, the compiler automatically assumes that the function we want is called as int. k = GetMax(i, j); //k = GetMax<int>(i, j); n = GetMax(l, m); //n = GetMax<long>(l, m); cout << k << endl; cout << n << endl; return 0; }

2 operation

[root@localhost test]# g++ test.cpp -g -o test [root@localhost test]# ./test 6 10

Class II template

1 code

#include <iostream> using namespace std; template <class Type> class compare { public: compare(Type a, Type b) { x = a; y = b; } Type max() { return (x > y) ? x : y; } Type min() { return (x < y) ? x : y; } private: Type x; Type y; }; int main(void) { compare<int> C1(3, 5); cout << "max:" << C1.max() << endl; cout << "min:" << C1.min() << endl; compare<float> C2(3.5, 3.6); cout << "max:" << C2.max() << endl; cout << "min:" << C2.min() << endl; compare<char> C3('a', 'd'); cout << "max:" << C3.max() << endl; cout << "min:" << C3.min() << endl; return 0; }

2 operation

[root@localhost test]# g++ test.cpp -g -o test [root@localhost test]# ./test max:5 min:3 max:3.6 min:3.5 max:d min:a

Parameter values of three templates

1 code

#include <iostream> using namespace std; // Template parameters contain other parameters that do not represent a type, such as a constant, which are usually basic data types template <class T, int N> class array { T memblock[N]; public: void setmember(int x, T value); T getmember(int x); }; template <class T, int N> void array<T, N>::setmember(int x, T value) { memblock[x] = value; } template <class T, int N> T array<T, N>::getmember(int x) { return memblock[x]; } int main() { array <int, 5> myints; array <float, 5> myfloats; myints.setmember(0, 100); myfloats.setmember(3, 3.1416); cout << myints.getmember(0) << '\n'; cout << myfloats.getmember(3) << '\n'; return 0; }

2 operation

[root@localhost test]# g++ test.cpp -g -o test [root@localhost test]# ./test 100 3.1416

Four description

The function of template has certain restrictions on file Engineering: the implementation of function or template must be declared in the same file as the prototype, that is, we can no longer store the interface in a separate header file, but must put the interface and implementation in the same file using the template.

3 December 2019, 14:05 | Views: 3541

Add new comment

For adding a comment, please log in
or create account

0 comments