C + + is a strongly typed language compared to C, which is more restrictive to the data type than C, which helps to avoid programmers making mistakes in their programming because of carelessness. For historical reasons, C + + still retains the reinterpret_ cast, static_cast, and so on for the mandatory type conversion of the keyword, but from the language to the trend of strong type, we should be in the programming work should be less use coercion type conversion, templates help us to achieve this goal. Another benefit of using forced-type conversions is that the program is more maintainable.
Let's take an example to learn how to reduce the cast in a program through a template. Figure 1 is a simplified example of a partial implementation of a two-way list (double-linked List, DLL), and a code fragment that uses a two-way linked list.
Class dll_t;
Class dll_node_t
{
friend class dll_t;
Public:
explicit dll_node_t ();
void data (void *_p_data) {p_data_ = _p_data;}
void *data () {return p_data_;}
Private:
dll_node_t *prev_;
dll_node_t *next_;
void *p_data_;
};
Class channel_t
{public
:
channel_t (): node ()
{
node_.data (reinterpret_cast <void * > (this));
Private:
dll_node_t Node_;
Figure 1
Where dll_node_t is a class encapsulation of a two-way linked list node. In addition to the PREV_ and next_ two member variables used to hold the previous and last node pointers, there is a p_data_ that holds the node data. Because the exact meaning of the data that the node holds depends entirely on the users of the linked list, the P_data_ type is defined as void* to accommodate any type of data. The data () function in rows 10th and 11 is used to set and get the value of the P_data_ variable separately. The code example in line 19th to 29th of the
Diagram uses fragments of the dll_node_t class for the channel_t class. In the constructor of the Channel_t class, the data () function is called to save the this pointer to the node's P_data_ variable by forcing type conversion. It is not hard to imagine that when you get the value in P_data_ through the data () function, you also have to convert it to a pointer of type channel_t (this part of the code is not listed in the diagram).
&NBSP
Figure 2 is a version that is overwritten with a template. It is believed that the reader can easily discern that there is no forced type conversion.
Template <typename t_node> class dll_t;
Template <typename t_data> class dll_node_t
{
friend class dll_t <dll_node_t <T_DATA> >;
Public:
explicit dll_node_t ();
void data (T_data *_p_data) {p_data_ = _p_data;}
T_data *data () {return p_data_;}
Private:
dll_node_t *prev_;
dll_node_t *next_;
T_data *p_data_;
};
Class channel_t
{public
:
channel_t (): Node_ ()
{
node_.data (this);
}
Private:
dll_node_t <channel_t> node_;
};
Figure 2
The above is the entire content of this article, I hope to be proficient with the use of templates to remove the casting help.