C ++ has the concept of class inheritance, which means an application that can implement the same functions as inheritance. So what is a C ++ class template? Is it similar to the usage of class functions? First, let's use the following code to introduce in detail how C ++ class templates are applied.
C ++ template code example:
- #include "stdafx.h"
- #include "Stack.h"
- #include < iostream>
- #include < string>
- #include < cstdlib>
- #include < stdexcept>
- int _tmain(int argc, _TCHAR* argv[])
- {
- try
- {
- Stack< int> intStack;
- Stack< std::string> stringStack;
- intStack.push(7);
- std::cout< < "intStack.top() = >"< < intStack.top()
< < std::endl;
- stringStack.push("Hello!");
- std::cout< < "stringStack.top() = >"< < stringStack.top()
< < std::endl;
- stringStack.pop();
- stringStack.pop();
- }
- catch(std::exception const& ex)
- {
- std::cerr< < "Exception: "< < ex.what()< < std::endl;
- return EXIT_FAILURE;
- }
- return 0;
- }
- Summary of the usage of the C ++ string segmentation Function
- How C ++ templates limit Actual Application
- Detailed description of the implementation of the C ++ reflection mechanism
- How to use C ++ to obtain the current path
- Discussion on the Application of C ++ array parameters
In this C ++ class template code, the statement [Stack <int> intStack;] shows the class template instantiation and defines a variable process. Like the function template instantiation, the class template instantiation must also provide the type of required parameters. Variables defined after instantiation can call member functions defined by class templates like common variables. You only need to note that the member functions of the class template will be instantiated only when called. For the intStack above, because only the push () member function is called, only the construction and analysis functions of the push member function are instantiated, except that they will be called by default ).
There are two advantages:
First, it can save space and time.
Second, for parameter types of each class template, the operation required by the template is required. For example, if you use a custom class MyClass as a class template Caculator <T> parameter. Because Caculator class templates require that parameter types support the "+" and "-" operations. However, your MyClass class only needs to use the "+" Operation and does not provide the "-" operation. Thanks to the above rules, your MyClass type can still be used as a Caulator <T> parameter. The premise is that you do not use "-" related member functions.
The above is our introduction to the application of C ++ class templates.