Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can optional<double> be implemented as 8-byte object?

Is it possible to implement std::optional such that sizeof(std::optional<double>) == 8 by somehow using that you can store characters in a NAN, see http://en.cppreference.com/w/cpp/numeric/math/nan? Are there implementations that do that? Can it be done in terms of the functionality that is available in the standard?

like image 426
Toby Brull Avatar asked Oct 18 '22 08:10

Toby Brull


2 Answers

I don't think this can be done because there is no rule preventing programs from utilizing and relying on the extra bits in NaN on their own. Then if you store the magic number into the optional it looks like it's not present instead of the application's special NaN.

like image 169
Mark B Avatar answered Nov 17 '22 07:11

Mark B


Answer is multifold.

First of all, it can not be implemented with the functionality available in Standard, since Standard says nothing of floating point implementation.

Second, for IEEE 754 floating points you can implement your own optional by specializing std::optional for doubles. However, this would mean that you exclude a valid value (NaN is a result produced by some arithmetic operations) from your range of values. However, diving deep into IEEE 754, you might choose a specific NaN representation (there are a lot of those!) as a no-value.

like image 26
SergeyA Avatar answered Nov 17 '22 07:11

SergeyA