C all type parameters

How to write a function that takes a generic type parameter in C? (e.g. int, a char ...)

+1
source share
8 answers

I personally would do it like this:

1) send a pointer to void * as the first parameter

2) send a second parameter that tells you what void * means (an enumeration for possibilities) and sets parameter 1 for this

This will force you to write ugly code with a lot of switches, but it can work if everything is done carefully and thoroughly tested.

Sort of:

// the enum:
BYTE_VALUE = 1; INT_VALUE = 2, CHAR_VALUE = 3 etc

// the function
int parse(void *arg, enum_type arg_type)
{
    if (arg == NULL) return -1;

    switch(arg_type)
    {
    case BYTE_VALUE:
        byte value = (byte) *arg;
        // do work here
    case INT_VALUE:
     // etc
    }

    return something;
}

Edit: It is assumed that you do not want the variational functions (which did not seem to be what you wanted)

+5
source

, .

  • : void . :

   myfunc(&7); 

, :

int x = 7;
myfunc(&x);
  • : Variadic. , , .

  • . , void, .

  • .


void myfuncchar (char c);
void myfuncint (int i);

, .

+2

printf. , .

printf("%d",  intvalue);
printf("%f",  floatvalue);
printf("%s",  stringvalue);

, .

+2

, . , . :

union foo {
char c;
int i;
}

struct foo f;
f.c = 'd';
function (f);
f.i = 23;
function(f);

int function(union foo f)
...

, , , , f.c, -, f.i . ( , undefined, - -, , .) , , , - .

, void *. , .

+1

, - , .

Laura , :

// the enum:
enum types{ int_val, char_val, float_val };
// the functions

int (*funcArr[3])(void*) = {NULL};


int to_do_if_int(void* input)
{
   return 0;
}

int to_do_if_char(void* input)
{
   return 0;
}

int to_do_if_float(void* input)
{
   return 0;
}

void initializer()
 {
   funcArr[int_val] = &to_do_if_int;
   funcArr[char_val] = &to_do_if_char;
   funcArr[float_val] = &to_do_if_float;
 }

int parse(void *arg, enum_type arg_type){    
   if (arg == NULL) return -1;

   (*funcArr[arg_type])(arg);

   return something;
}
+1

void* . , , memcpy, - . , ( , ), , "" ( , , memcpy ), void* - - , - , . , , , , . memcpy, , , .

0
source

Best to use templates. You can use void pointers, but this can lead to other problems if they are not executed correctly. The best thing to do is go HERE to read the tutorial and try it yourself. You should have no problem understanding the concept of templates.

-1
source

Source: https://habr.com/ru/post/1723276/


All Articles