Search code examples
c++data-structurescastingcompiler-construction

Implementing a symbol tables to store values for different types C++


I'm implementing a compiler in C++ and am at the AST stage. I now need to add in the symbol_entry, a value for that varible (it already has type). But how do I keep values of different sizes in an attributes of the class when I don't know the type. My current idea is to declare an attribute "val_pointer" of type void* in the symbol_entry, and cast for example from int* to void* and back. My understanding is that this can be done because pointers are all of the same size. Will this work? And also, is this way of allocating an int* separately each time efficient? I think that it would be better if I store create these int* from a contiguous block of memory, but I want to save space too.


Solution

  • One solution is to use tagged unions. For example:

    enum Type
    {
        tInt,
        tDouble
    };
    
    struct Data
    {
        Type    type;
        union
        {
            int Int;    // only valid when type is tInt
            double Double;  // only valid when type is tDouble
        } as;
    };
    

    Note that this isn't the best solution available in C++. You may want to look into std::variant, which has some advantages when compared to a raw tagged union, see Where to use std::variant over union?.

    Another approach might be to have a class hierarchy, where each of your data types inherits from a basic Object type.