"Szabolcs Nagy" <ns*******@gmail.coma écrit dans le message de news:
11**********************@50g2000hsm.googlegroups.c om...
>
jxh wrote:
>For a different example, a template function based quick sort
implementation could allow the compiler to inline the call to the
comparison function.
/* generic_qsort.c */
PREFIX(qsort)(TYPE *arr, size_t len) {
...
if (LESS(*right, pivot)) {...}
...
}
/* int_qsort.c */
#define PREFIX(s) int_##s
typedef int TYPE;
static inline int LESS(int a, int b) {return a < b;}
#include "generic_qsort.c"
#undef PREFIX
not much longer than c++ templates imho
macros are ugly though
generic)qsort is not generic enough: the LESS function and the TYPE typename
should be macroized with PREFIX as well, to allow for multiple
instantiations of generic qsort routines for different types in the same
module.
/* generic_qsort.c */
void PREFIX(qsort)(PREFIX(TYPE) *arr, size_t len) {
...
if (PREFIX(LESS)(*right, pivot)) {...}
...
}
/* mymodule.c */
#define PREFIX(s) int_##s
typedef int int_TYPE;
static inline int int_LESS(int a, int b) {return a < b;}
#include "generic_qsort.c"
#undef PREFIX
....
#define PREFIX(s) string_##s
typedef const char * string_TYPE;
static inline int string_LESS(const char *a, const char *b) {return
strcmp(a, b) < 0;}
#include "generic_qsort.c"
#undef PREFIX
TYPE, LESS and QSORT could be made macros themselves, with a similarly ugly
implementation/instantiation:
/* generic_qsort.c */
void QSORT(TYPE *arr, size_t len) {
...
if (LESS(*right, pivot)) {...}
...
}
/* mymodule.c */
#define QSORT int_qsort
#define TYPE int
#define LESS(a, b) ((a) < (b))
#include "generic_qsort.c"
#undef PREFIX
#undef TYPE
#undef QSORT
....
#define QSORT string_qsort
#define TYPE const char *
#define LESS(a, b) (strcmp(a, b) < 0)
#include "generic_qsort.c"
#undef PREFIX
#undef TYPE
#undef QSORT
Some better mechanism would certainly help writing type safe generic code:
/* hypothetical example */
/* generic_qsort.h */
template generic_qsort(qsort, type, isless) {
typedef type;
int isless(type a, type b);
void qsort(type *arr, size_t len) {
...
if (isless(*right, pivot)) {...}
...
}
}
/* mymodule.c */
#include "generic_qsort.h"
static inline int int_less(int a, int b) {return a < b;}
static inline int string_less(const char *a, const char *b) {return
strcmp(a, b) < 0;}
generic_qsort(int_qsort, int, int_less);
generic_qsort(string_qsort, const char *, string_less);
--
Chqrlie.