mercredi 21 décembre 2022

How to create an interface in C that can work on two identical structs with differently named fields

Question Background

Consider a scenario in which I have two structs. Both consist of three fields for doubles. The only difference is the names used to refer to these fields. The first struct is for non-descript Tuples and the components are to be named x, y, and z. The second struct is for RGB values and the components are to be named red, green, and blue. Both of these structs need to have an interface defined for them such that operations such as vector/componentwise addition and scalar multiplication can be performed.

The Question

The problem? It seems terribly inelegant to copy and paste identical code for both of these structs only to change the naming scheme (x vs. red, y vs. green, z vs. blue). Ideally it would be possible in the interface function definitions to reference the fields of the struct (x or red) without having to name the field. Is this possible? If not then what other options are avaiable to me without changing the requirements? I include the struct definitions below along with some examples of their desired use with the possibly impossible interface I describe in this question.

Non-descript Tuple Struct

typedef struct
{
    /** The first coordinate */
    double x;

    /** The second coordinate */
    double y;

    /** The third coordinate */
    double z;

} Tuple;

RGB Tuple Struct

typedef struct
{
    /** The first coordinate */
    double red;

    /** The second coordinate */
    double green;

    /** The third coordinate */
    double blue;
} Tuple;

Example Usage

Tuple * genericTuple = createVector( 1, 2, 3 ); // create a generic Tuple
printf("%lf", genericTuple->x); // should print 1

Tuple * rgbTuple = createColor( 1, 2, 3 ); // create an rgbTuple
printf("%lf", rgbTuple->red); // should also print 1

Aucun commentaire:

Enregistrer un commentaire