C function that allows two data types

Viewed 105

Maybe its just a dumb question but I was wondering if there is a way to allow two data types in the same function parameter, sort of polimorphism that in the end does the same stuff, just to filter out some garbage input.

typedef enum
{

} type1_t;

typedef enum
{

} type2_t;

void myfunc(typex_t foo)
{

}
2 Answers

You may consider a different approach, involving one of C11 features.

A generic selection

Provides a way to choose one of several expressions at compile time, based on a type of a controlling expression.

You'll end up with some code duplication, but also a common "interface".

#include <stdio.h>

void myfunc_int(int x){
    printf("int: %d\n", x);
}
void myfunc_float(float y){
    printf("float: %f\n", y);
}

#define myfunc(X) _Generic((X),     \
    int : myfunc_int,               \
    float : myfunc_float            \
) (X)

int main(void)
{
    myfunc(3.14f);

    myfunc(42);

//    myfunc(1.0);
//           ^ "error: '_Generic' selector of type 'double'
//                    is not compatible with any association"
}

Testable here.

Tagged Union

You could use a union:

typedef union
{
    type1_t t1;
    type2_t t2;
} UnionType;

You need to somehow know if t1 or t2 is active. For this you can pass an additional enumeration value (A distinct value for each type you want to allow):

enum types
{
    TYPE1,
    TYPE2
};

Combine it to a struct, and there you have your typex_t:

typedef struct
{
    enum types type; // this is also called a type tag
    UnionType content;
} typex_t;

Or more compact (nonstandard)

typedef struct
{
    enum { TYPE1, TYPE2 } type;
    union { type1_t t1; type2_t t2; } content;
} typex_t;

This whole struct union construct is also called a tagged union.

Related