CaggianoLabs

“Experimenting on the Net”


Offrire il Linus Torvalds Award alla Free Software Foundation
è un po' come dare il Premio Han Solo all'alleanza ribelle di Guerre Stellari

Richard Stallman

Login

Register ?

Power

CSS Valido!
60% Geek
Tophost
Creative Commons License

Template in C

Tags: template,c,c ,programmazione


Mi ่ venuto in mente un modo di implementare i template in C ...

Esempio:


/**
 * How to implements templates in C
 * by Marco Caggiano
 **/

#define my_template_function(type, dest, x) 
do { 

   type *t = malloc((x) * sizeof(type)); 

   assert(t != NULL); 

   dest = type; 

} while(0);

int main(void){

   int    *idest = NULL;
   float *fdest = NULL;

   my_template_function(int,    idest, 1000);
   my_template_function(float, fdest, 1000);

   free(idest);
   free(fdest);

   return 0;

}




Come vedete quel codice funziona con qualsiasi tipo ....
Mi vengono in mente altre applicazioni:

[code=C]
/**
 * How to implements templates in C
 * by Marco Caggiano
 **/

#define stack_push(type, stack, element) \
do { \

   ++(stack)->lastElement = (element); \

   (stack)->size = ((stack)->lastElement - (stack)->firstElement); \
   (stack)->size /= sizeof(type); \
\
}while(0);

#define stack_pop(type, stack, ret) \
do { \

   *(ret) = *(stack)->lastElement--; \

   (stack)->size = ((stack)->lastElement - (stack)->firstElement); \
   (stack)->size /= sizeof(type); \
\
}while(0);

#define def_new_stack(type) \
typedef struct stack ## type { \
\
   type *firstElement; \
   type *lastElement; \
   int size; \
\
}Stack ## type ;

/* ... Altro codice ... */

def_new_stack(float);
def_new_stack(int);

int main(void) {

   Stackint    *si = init_stack(int);
   Stackfloat *sf = init_stack(float);
   int    ir;
   float if;

   stack_push(int, si, 5);
   stack_push(float, si, 6.7);

   stack_pop(int, si, &ri);
   stack_pop(float, si, &rf);

   printf("%d,%0.2f\n", ri, rf);

   return 0;

}

[/code]


programmer


I template C non sono altro che macro C con qualche nozione di semantica.

Hanno cercato di emulare MacLisp ma non ce l'hanno fatta. Quando senti "C " e "metaprogramming" nella stessa frase senza che vi sia apposto un "non è" vuol dire che stai parlando con qualcuno che mette prefissi a caso solo perché fanno fico.



programmer


Il tuo blog mangia automagicamente il doppio .



programmer


Bello mangia anche il singolo%uFE62(più)



programmer


Non fa neanche utf8. Proviamo qualcosa di nasty:

<strong>strong!</strong>

nasty &amp; nasty



programmer


Meno male.



admin


Immaginavo che i template Cpp, in realtà, fossero macro C.
Da qui è nata l'"idea".

Comunque non metto i prefissi perchè fa fico, l'ho messo, ma penso che sia sbagliato ora come ora non ricordo perchè lo abbia messo; forse credevo di incrementare il puntatore, ma mi sa che ho ottenuto un altro effetto ...
Comunque grazie per il commento.