Search code examples
cstructunions

Uniform handle parameter for multiple datatypes in C


This is in C. I have a handle which I use throughout many files (let's call it type_handle), which is an enum presently, but currently I would need to extend it to support a typedef-ed struct (called my_type) as well. Since many functions take type_handle as an input parameter, I don't want to change the design majorly so that I need to redo all the files. So my idea is to pass int, float, double and then my_type. I want to have some sort of a union function of all types I want, so that I don't need to modify functions taking type_handle. How should I design this?

typedef enum
{
    INT  = MPI_INT,
    INT8 = MPI_INT8_T,
    INT16 = MPI_INT16_T
}
types_t;

typedef union {
    my_type dtype;
    types_t etype;
} type_handle;

I want to design this in a way such that any_func(type_handle type) could accept any_func(INT) as well as any_func(dtype) where dtype is say a derived datatype of type my_type.


Solution

  • When using a union in C you need some way to know which member to use. C itself cannot tell you which element of your union is the one you assigned. This will be confusing to explain, since you are already dealing with types, but the idiom would be:

    struct {
       what_is_in_the_union_t what;
       union {
           type_a a;
           type_b b;
           ...
       } u;
    };
    

    Where what_is_in_the_union_t is your own enum of { TYPE_A, TYPE_B, ... }. As I said, this will expand in a confusing way in your example because your inner type_a is already a types_t.