using Num = std::variant<int64_t, double>;
std::vector<int64_t> intsOnly = makeInts();
std::vector<Num> intsAndFloats = makeIntsAndFloats();
int64_t iResult = 0;
for (auto i: intsOnlys) {
iResult += i;
}
double dResult = 0.0;
for (auto d: intsAndFloats) {
dResult += extractValue(d); // function always returns double type.
}
assert(iResult == int64_t(dResult));
If the variable intsAndFloats
contains only ints, will the above assertion always hold, or is the double type not able to represent certain int64_t values, in some cases?
My usecase is that I'm creating a toy compiler, and I want the result type of an addition to be int
or real
, depending on the arguments to a function add
. Like:
// If any of the arguments is a real, then the result is a real; else, it's an int.
(add $a $b $c ... $n)
Currently, I'm iterating over the argument list twice: once to see if there are doubles present, and another to perform the actual addition. I'd like to avoid that, if possible.
// Iterate over the list once, to set hasFloat. Then ...
if (hasFloat) {
double result = 0.0;
for (auto i: args) {
result += isInt(i) ? getInt(i) : getFloat(i);
}
return returnFloat(result);
} else { // has no floats.
int64_t result = 0;
for (auto i: args) {
result += getInt(i);
}
return returnInt(result);
}