Is it possible to convert foo from float to long (and vice versa)?
auto foo = float(1234567891234.1234);
cout << "foo: " << foo << endl;
foo = long(1234567891234.1234);
cout << "foo: " << foo << endl;
The output is always:
foo: 1.23457e+12 foo: 1.23457e+12
Not in the way you wrote it. First,
uses auto type deduction rules to infer the type of the RHS, and the result is
float
. Once this is done, the type offoo
isfloat
and it is set in stone (C++ is statically typed, unlike e.g. Python). When you next writethe type of foo is still
float
and it is not magically changed tolong
.If you want to emulate a "change" of type you can at most perform a cast:
or use an additional variable
but be aware of possible precision loss due to floating point representation.
If you have access to a C++17 compiler, you can use an
std::variant<long, float>
, which is a type-safe union, to switch between types. If not, you can just use a plain old union likeLive on Coliru
Or, you can use a type-erasure technique like
Live on Coliru
The modern version of the code above can be re-written with a
std::shared_ptr
likeLive on Coliru
A
std::unique_ptr<void>
won't work as onlystd::shared_ptr
implements type-erasure.Of course, if you don't really care about storage size etc, just use 2 separate variables.