Andy
Andy

Reputation: 3849

How do I represent undefined numbers in C++ using large values?

In C++ I want to use a pair of large values to represent an undefined number:

void setUndefined(float& a) {
    a = set_undefined_value;
}

bool isUndefined(float a) {
    return a > is_undefined_value;
}

I want to use this approach for all numeric types, and from templatized code, so I was thinking along the lines of a template:

template<typename T>
    class Undefined {
    public:
        static T set_undefined_value() {
            NOT_IMPLEMENTED_FOR_THIS_TYPE_YET;
        }
        static T is_undefined_value() {
            NOT_IMPLEMENTED_FOR_THIS_TYPE_YET;
        }
    };

    // Template specialization for all numeric types: ... 

How do I find good pair of values for all numeric types?

Is there e.g. some way I can use the std::numeric_limits::max() template?

If I write undefined values to file will they be portable across computers and OSes?

Upvotes: 0

Views: 798

Answers (1)

Minthos
Minthos

Reputation: 900

For floats and doubles pick a bit pattern for each that corresponds to NaN in IEEE754. Then you can make a macro for testing nan on all imaginable compilers and with all imaginable floating point optimizations.

For signed integers use the most negative value (0x80...)

For unsigned integers use the most positive value (0xFF...)

Upvotes: 2

Related Questions