In high-level languages, we use overloading for functions, which is used in functions with different functions but with the same number of parameters, and templates are needed for different types and the same number of parameters
C++ applet
- #include<iostream>
- using namespace std;
- template <class T>
- T max(T a,T b)
- {
- return a>b?a:b;
- }
- int main()
- {
- int a,b;cin>>a>>b;
- cout<<max(a,b);
- return 0;
- }
Copy code This is a simple example: the keyword template<class T> is the beginning of a template structure, so that we don't need to write several C++ code with the same function repeatedly when looking for the maximum value Note that when calling a function, its type is automatically matched. It doesn't need to be shown. The above is the most basic usage, but we will encounter the following situations
- #include<iostream>
- using namespace std;
- template <class T,class E>
- E max(T a,E b)
- {
- return a>b?a:b;
- }
- int main()
- {
- int a;float b;cin>>a>>b;
- cout<<max(a,b);
- return 0;
- }
Copy code What to do when our function needs two different types, I think you can understand it after reading the above code. But anyway, what they have in common is that the types are automatically matched. In fact, we also have mistakes, if we can't match the type well, that is, "the bull's head is not right", then the compiler's automatic matching will change the parameter type according to the rules of implicit type conversion, which will eventually lead to the loss of accuracy of the result. Look at the code, you can try.
- #include<iostream>
- using namespace std;
- template <class T,class E>
- E max(T a,E b)
- {
- return a>b?a:b;
- }
- int main()
- {
- int a;float b;cin>>a>>b;
- cout<<max(a,b);
- return 0;
- }
Copy code The above content is not very difficult, but there are also many places that can be explored, I don't know what your opinions are |
|