The task is as follows, I have many structures that are often stored in lists. I would like to find a solution that allows you to create lists of structures of different types in the same way. Those. Is it possible to do something like a template class in C? Now I use macros for this.
- I unfortunately did not work with this, but there is an assumption to use pointers with some type field to determine the type. And it is still not clear why this is necessary, if it is because of the call of a multitude of functions, is it not better to do a redefinition of functions with different input parameters and some common function with the calculation and transfer to it a reference to the comparison function or what is required there. - Sergey
|
2 answers
Only through macros unfortunately. The first implementation of C ++ at one time was also written in C and using macros, so this option is not the worst.
- Because of the macros, in my opinion, the readability of the code drops dramatically. - Nicolas Chabanovsky ♦
- Because of macros, not only readability falls. But if you need to do something that is not done in another way, then you need to write a macro so that readability is acceptable. - IAZ
|
struct gen_list { struct gen_list *next, *prev; int value_type; void *value; }; struct gen_list *list_elem;
In value, put a pointer to the structure in the list, in the value_type type of structure. next / prev - pointers to the next / previous one in the list (as usual) To access the structures:
switch (list_elem->value_type) { case 1: p_stru1 = (t_stru1 *)(list_elem->value); ... }
Of course, structure types are predefined at compile time.
- This solution is not suitable. Since this is the same as macros. - Nicolas Chabanovsky ♦
- 2The question was not to create a list for storing different types of structures (an analogue of inheritance). And to create a list in which structures of one type are stored, but to be able to create on the basis of it another list with other structures (an analogue of abstracting compile-time — templates). - IAZ
|