Is there a standard C header file which assigns a numeric value to all of the primitive types?

前端 未结 2 1468
说谎
说谎 2020-12-21 10:51

I have some code which performs differently depending on the underlying data type. EG:

void *some_data = obtain_data();
int data_type = obtain_data_type();
         


        
相关标签:
2条回答
  • 2020-12-21 11:44

    There are no such standard constants, no. There's a lot of things in C that you'd think would be standardized, but aren't.


    As a side note, you could take the first steps towards a bit more modern C programming by using the C11 _Generic keyword and implementing polymorphism behavior instead of using run-time checking of such enums. In fact, you can get rid of the enum entirely:

    // variant.h / variant.c
    #include <stdio.h>
    
    typedef void print_func_t (const void* data);
    
    typedef struct
    {
      void* data;
      print_func_t* print;
    } variant_t;
    
    
    void print_char  (const void* data) { printf("%c",  *(const char*)  data); }
    void print_short (const void* data) { printf("%hd", *(const short*) data); }
    void print_int   (const void* data) { printf("%d",  *(const int*)   data); }
    
    void print (const variant_t* var)
    {
      var->print(var->data);
    }
    
    #define variant_init(var) { \
      .data = &var, \
      .print = _Generic((var), char: print_char, short: print_short, int: print_int) \
    }
    

    Caller:

    int main() 
    {
      char c = 'A';
      short s = 3;
      int i = 5;
    
      variant_t var[3] =
      {
        variant_init(c),
        variant_init(s),
        variant_init(i)
      };
    
      for(size_t i=0; i<3; i++)
      {
        print(&var[i]);
        printf(" ");
      }
    
      return 0;
    }
    
    0 讨论(0)
  • 2020-12-21 11:49

    This is called in C++ a variant type. There are many libraries that do this for you, such as:

    1. QVariant from Qt
    2. Boost any

    But remember that there's a price to pay when using such a library. Things are not most efficient when you use variants, but some times it's necessary, such as when you use OPC/UA protocols.

    0 讨论(0)
提交回复
热议问题