Search code examples
c++data-structurestypesenumerated-types

Is there a way to create an enumerated data type for non integers?


I'm writing a simple conversion program and I would like to create something similar to this:

//Ratios of a meter
enum Unit_Type
{
  CENTIMETER = 0.01, //only integers allowed
  METER = 1,
  KILOMETER = 1000
};

Is there a simple data structure that will allow me to organize my data like this?


Solution

  • Not really. While C++11 introduces some really neat new things for enums, e.g. specifically being able to assign them some specific internal data type (like char), there's no way to add floats or any other non-integer type.

    Depending on what you're actually trying to do, I'd use some plain old struct for this:

    struct UnitInfo {
        const char *name;
        float       ratio;
    };
    
    UnitInfo units[] = {
        {"centimeter",   0.01f},
        {"meter",        1},
        {"kilometer", 1000},
        {0, 0} // special "terminator"
    };
    

    You're then able to iterate over all your available units using a pointer as your iterator:

    float in;
    std::cout << "Length in meters: ";
    std::cin >> in;
    
    // Iterate over all available units
    for (UnitInfo *p = units; *p; ++p) {
        // Use the unit information:
        //  p[0] is the unit name
        //  p[1] is the conversion ratio
        std::cout << (in / p[1]) << " " << p[0] << std::endl;
    }
    

    If this is about using those ratios together with actual values (like 100 * CENTIMETER), then C++11's user-defined literals might be something for you:

    constexpr float operator"" _cm(float units) {
        return units * .01f;
    }
    

    This could then be used like this:

    float distance = 150_cm;