I have a different objects, like this:
typedef struct { int32_t info ; } item1_properties_t ;
and
typedef struct { int32_t info ; } item2_properties_t ;
the objects are held in containers. I want to introduce a function that returns these objects (i.e. a const pointer) with minimum casts (working in C). I thought of having the function return the type and a void pointer, expecting the caller to cast correctly but I don't really like it. Do you have better ideas?
It doesn't matter that you fill your structures from XML.
What is relevant is that you have a container containing objects of mixed type.
To be able to process the different properties (that have different types depending on the type of object) you do need some part of the code to care about the object type.
So even if you have a generic void pointer for each object, you need a function: get_type_of_object(generic_ptr)
And while a generic get_property(generic_ptr) function could contain a switch statement to figure out what type of object so it knows what properties to return, it would have to return a generic answer.
So the caller of get_property(generic_ptr) would have to also contain a switch statement to figure out what to do with the returned value from that generic get_property() function.
So then the caller could already from the start have had a switch statement that decided the type of object, and called a specialized get_xx_property() or get_yy_property() in which case it will directly receive a correct property struct.
The switch() statements can be replaced by manually created virtual functions - i.e. every object contains a couple of function pointers: print_me() process_properties() load() save()
But as soon as you want a generic loop to retrieve properties from an object of unknown type and then do something with these properties, then that loop needs code to decode type, making the code non-generic.
You must figure out where in your design you want to introduce that decoding of data type, or if you can move all processing into type-specific functions, so that you can have all objects changed into a reference to a type-specific function pointer table and a list of type-specific information that the type-specific functions knows how to handle. Then the type-specific functions can directly perform a type cast to their specific type since only the correct object type will point to that specific function pointer table.
If you happen to intend to use a 8051 chip, then function pointers are bad because of the special code generation used by the C51 compiler, so you have to settle for switch statements and just figure out where to place them.
Thanks for the reply. I'm using an ARM type processor so it's OK. Thanks all the time.