Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to assign a unique number to a type in C?

Tags:

c

types

I am coming from a C++ background, and have recently taken up C. I am am having trouble assigning a number to a type (or vice versa); what I need is some way to assign a unique ID to a type, preferably starting from 0. My goal is to have a function (or macro) that indexes an array based on a passed-in type, which I believe to only be achievable through macros.

Also, since I use the sizeof() the type which I need to be passed in, it makes using enums as an alternative difficult. If I were to pass the enumerator to the function/macro instead, then I would have to get the type from the number, the exact opposite (but maybe easier) problem.

Is this even possible in C? I have tried researching this question, but have not found any answer to this problem particularly, which I was able to do in C++ with templates, like so:

int curTypeIdx = 0;

template <typename T>
struct TypeHandle {
    static int const val;
}

template <typename T>
int const TypeHandle<T>::val = curTypeIdx++;

The reason for this is that I am building an ECS. I have an EntityManager struct, which is supposed to contain arrays of components. Since I plan for this to be general-purpose, I defined an upper limit of components (MAX_COMPONENTS) and have an array of char*s of length MAX_COMPONENTS. At a basic level, The goal is to give the user of the EntityManager the ability to define their own components, and store them in these generic arrays.

If there is any other way to

Thank you all for any advice.

like image 287
mrFoobles Avatar asked Aug 17 '18 21:08

mrFoobles


1 Answers

If you are OK with enumerating ALL supported types once( and update the list if language comes up with new types), then you can use the stringize functionality of C macros and an array of strings to achieve what you want.

#define GET_TYPE_ID(type) get_type_id(#type)
const char *type_strings[] = { "char", "unsigned char", "short" /* so on.. */};

int get_type_id(const char* type_string) {
    for( int i = 0; i < sizeof(type_strings)/sizeof(const char*); i++) {
         if ( strcmp(type_string, type_strings[i]) == 0 ) return i;
    }
    // Should never reach here if you have taken care of all types and 
    // don't pass in illegal types.
}

Now you can get an integer ID for each type with GET_TYPE_ID(int), GET_TYPE_ID(char) and so on.

like image 113
Pavan Manjunath Avatar answered Oct 19 '22 08:10

Pavan Manjunath