statueuphemism statueuphemism - 4 years ago 73
C++ Question

C++ "Floating Point Enum"

I am looking for a solution using the C++03 standard (I am constrained to using this version of the standard for several years yet). Solutions for C++11 are also welcome, but will not be "accepted" as the answer to this question.

What is a simple, concise way that I can represent a set of related constant floating point values as a single type (similar to an enum) to ensure type-safety without incurring significant overhead and still allow me to operate on the values as floats directly?

The end result is that I would like to be able to do something like the following:

enum FloatingPointEnum
{
VALUE1 = 0.1234f,
...
VALUEN = 0.6789f
};


float SomeFunction(FloatingPointEnum value)
{
float new_value;
/* perform some operation using "value" to calculate "new_value" */
new_value = static_cast<float>(value); // <- a simplistic example
return new_value;
}


While I can think of several solutions, none of them are as clean/simple/straightforward as I would like and I figure that someone must already have an elegant solution to this problem (yet I cannot seem to find one in my searching).

EDIT:

I would like the following call to SomeFunction with a value that is not specified directly as a value from the enumerated type to fail to compile:

float nonEnumeratedValue = 5.0f
SomeFunction(nonEnumeratedValue);

Answer Source

someone must already have an elegant solution to this problem

There are lots of problems that have no elegant solution (and many that have no solution at all). What makes you think this problem has one? This assumption is very faulty. The closest you can get is to use a wrapper class.

class FloatingPointEnum {
    float f;
    FloatingPointEnum(float arg) : f(arg) {}
public:
    static const FloatingPointEnum Value1;
    static const FloatingPointEnum Value2;
    operator float() const { return f; }
};
const FloatingPointEnum FloatingPointEnum::Value1(0.1234f);
const FloatingPointEnum FloatingPointEnum::Value2(0.6789f);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download