How to achieve function overloading in C?

前端 未结 14 2528
清歌不尽
清歌不尽 2020-11-22 03:16

Is there any way to achieve function overloading in C? I am looking at simple functions to be overloaded like

foo (int a)  
foo (char b)  
foo (float c , i         


        
14条回答
  •  孤城傲影
    2020-11-22 04:05

    As already stated, overloading in the sense that you mean isn't supported by C. A common idiom to solve the problem is making the function accept a tagged union. This is implemented by a struct parameter, where the struct itself consists of some sort of type indicator, such as an enum, and a union of the different types of values. Example:

    #include 
    
    typedef enum {
        T_INT,
        T_FLOAT,
        T_CHAR,
    } my_type;
    
    typedef struct {
        my_type type;
        union {
            int a; 
            float b; 
            char c;
        } my_union;
    } my_struct;
    
    void set_overload (my_struct *whatever) 
    {
        switch (whatever->type) 
        {
            case T_INT:
                whatever->my_union.a = 1;
                break;
            case T_FLOAT:
                whatever->my_union.b = 2.0;
                break;
            case T_CHAR:
                whatever->my_union.c = '3';
        }
    }
    
    void printf_overload (my_struct *whatever) {
        switch (whatever->type) 
        {
            case T_INT:
                printf("%d\n", whatever->my_union.a);
                break;
            case T_FLOAT:
                printf("%f\n", whatever->my_union.b);
                break;
            case T_CHAR:
                printf("%c\n", whatever->my_union.c);
                break;
        }
    
    }
    
    int main (int argc, char* argv[])
    {
        my_struct s;
    
        s.type=T_INT;
        set_overload(&s);
        printf_overload(&s);
    
        s.type=T_FLOAT;
        set_overload(&s);
        printf_overload(&s);
    
        s.type=T_CHAR;
        set_overload(&s);
        printf_overload(&s); 
    }
    

提交回复
热议问题