Search code examples
c++user-interfacedata-structuresstore

How to store numerical values which can get assigned with strings


I am creating a GUI structure, where obviously I have two main parameters: width and height. (For simplification lets pretend these are my only values.) I am developing this in C++.

I have an XML file which builds up the structure hierarchy of the widget and I have a CSS like file, which gives the values (width and height) for each node in the structure. When the program starts I read and parse these files. Now my question is about what is the best practice to store the variables from my CSS like file?

If the width and height parameters would only be numbers, than the answer is easy, since I store them in an int for example. But in my case in my CSS like file I can give the value "parent" or "child" to width and height, which means that their dimension is the same as their parent or child node.

A simple solution would be to assign some numbers (negative numbers for example) to "parent" and "child", while parsing them, but this doesn't look to elegant.

An other solution, which came into my mind to create a struct where I can store two bool variable and one int for example and the bool variables would indicate if it should be "parent" or "child", but for some reason this also doesn't look too elegant for me, but I might be wrong.

Does anybody have any advice, maybe other solutions or knows a best practice in cases like this? All help, hints are much appreciated!


Solution

  • One solution: store a tuple of number and units. Use a fixed set of units which includes special units such as PARENT and CHILD as well as whatever your default unit is (e.g., PIXELS). This representation would easily extend to other CSS-like dimensional units (e.g., EMS, PICAS, whatever.)

    struct Dimension
    {
      typedef int value_type;
    
      enum struct units_type { PARENT, CHILD, PX };
    
      units_type units;
      value_type value;
    };
    

    For special units such as PARENT or CHILD, your logic can ignore whatever value is stored.