您可以做的是使用多态对象。定义如下结构:
#define INT_TYPE 0
#define DOUBLE_TYPE 1
//more type constants
typedef struct Vector2D {
    int type;
} Vector2D;
typedef struct Vector2D_int {
    Vector2D super;
    int x, y;
} Vector2D_int;
typedef struct Vector2D_double {
    Vector2D super;
    double x, y;
} Vector2D_double;
//more typed vector structures
然后,您可以编写函数来接受Vector2D指针,检查它们各自的类型字段并将它们转换为适当的类型变量以访问有效负载数据。
double Vector2D_length(const Vector2D* vector) {
    if(vector->type == TYPE_INT) {
        const Vector2D_int* intVector = (Vector2D_int*)vector;
        return sqrt(intVector->x * intVector->x + intVector->y * intVector->y);
    }
    if(vector->type == TYPE_DOUBLE) {
        const Vector2D_double* doubleVector = (Vector2D_double*)vector;
        return sqrt(doubleVector->x * doubleVector->x + doubleVector->y * doubleVector->y);
    }
    //other cases follow
}
这是手工编码的多态性。您只需要确保该type字段始终设置为正确的值(在创建类型化向量时设置一次)。
这种方法对您的第二个想法的优势在于,您不必在另一个变量中传递向量的类型,这会使使用向量变得乏味且容易出错。
作为替代方案,您可以将type字段定义为包含指向函数指针结构的指针。您将为您定义的每个类型化 Vector 类型创建一个此函数指针结构的对象,并使用它来查找要与给定向量一起使用的函数。这种方法将非常接近 C++ 在幕后所做的。