dimanche 19 juin 2022

Where to put implementation templates realized by C macros?

I want a write a C library with macro-templates depending on a type.

A very simplified example for the header file:

#define PAIR_TEMPLATE(Type) \
typedef struct { Type a[2]; } PAIR_ ## Type; \
Type Pair_ ## Type ## _Sum (PAIR_ ## Type *pPair); \

PAIR_TEMPLATE (char)

PAIR_TEMPLATE (int)

This should expand to

typedef struct { char a[2]; } PAIR_char;
char Pair_char_Sum (PAIR_char *pPair);

typedef struct { int a[2]; } PAIR_int;
int Pair_int_Sum (PAIR_int *pPair);

The implementation for Sum can also be templated:

#define PAIR_Sum_TEMPLATE(Type) \
Type Pair_ ## Type ## _Sum (PAIR_ ## Type *pPair) { \
  return (Type) (pPair->a [0] + pPair->a [1]); \
}

Please note that this is only a very simplified example. My real template will have multiple other functions and will be also applicable for almost any struct type. Think of it as of a template for a dynamic array.

My library itself will use this template for some data types. On the other hand, the user of the library should also be able to use this template for other types.

Now I am facing a design problem:

If I put the implementation template (not the header template!) into a separate code file which is supposed to be compiled in a translation unit different from the user's code, it will be difficult for the user to expand the implementation template for his own types.

On the other hand, if I put the implementation template into the library header file such that the user of my library will expand the implementation in the same translation unit, then he will have difficulties ensuring that, for every type, there is at most one implementation expanded.

Is there a good design solution for this conflict? Thank you.

Aucun commentaire:

Enregistrer un commentaire