C : send different structures for one function argument

后端 未结 2 549
日久生厌
日久生厌 2021-01-13 19:13

I have a function that draws a circle using OpenGL, I would like to pass it a structure containing the x and y coordinates and the radius. The problem is this same function

2条回答
  •  无人及你
    2021-01-13 19:43

    Only if the function accepts a void* as the argument, and then you cast the void* to the correct pointer type in the function before dereferencing it to access the data within.

    typedef enum
    {
        type1, type2, type3
    } datatype;
    
    void foo(void* data, datatype type)
    {
        switch(type)
        {
            case type1:
            // do something with data by casting it to the proper type
            break;
    
            // ... other cases here
        }
    }
    

    However, by doing so you will a) need to pass another argument that indicates the original type being casted to void* before being passed, and b) you are abandoning the type system which is hardly ever a good idea and should always be avoided.

    If you take this approach, highly recommend creating three "wrapper" functions that take the correct types before calling the function (that takes the void*) internally. Make it a strict convention to never call the void* function directly; only call the wrapper. In this fashion, you still have the type system to help out with compilation errors.

    void bar1(someStruct* data)
    {
        foo((void*) data, type1);
    }
    void bar2(someOtherStruct* data)
    {
        foo((void*) data, type2);
    }
    void bar3(yetAnotherStruct* data)
    {
        foo((void*) data, type3);
    }
    

提交回复
热议问题