I have this Union declared in a library that I wrote some time ago. I didn't create this union myself, it came from someone as an answer to a question on one of these forums. It's been so long, I cannot remember.
union cTime {
double seconds;
class milli_t {
double seconds;
public:
milli_t &operator=(double ms) {
seconds = ms / 1000.0;
return *this;
}
operator double() const { return seconds * 1000; }
} millis;
};
I can use this union to convert between Seconds and Milliseconds in this way
cTime time;
time.millis = 14000;
long seconds = time.seconds;
OR the other direction
cTime time;
time.seconds = 35;
long milliseconds = time.millis;
This gives me the freedom to work with the time variable within either context, seconds or milliseconds, then pull out of the variable, whichever version of the value I want.
I am oversimplifying my use case, but what I wanted to make sure to clarify is that what matters, is that I can declare a variable as cTime, assign it a value in either unit, work with the value and change it etc. in either unit, then when I need to return the value, or use it in whatever context ... I can simply use the variableName.unit and it comes back in that unit.
Obviously, seconds get rounded etc., but that's ok.
What I would like to do, is somehow expand the union to include the ability to also get microseconds from the datatype so that I can flexibly do anything such as
cTime time;
time.micros = 254000;
long seconds = time.seconds;
long milliseconds = time.millis;
etc.
Does anyone know if this is possible? If not with this union structure, then maybe with an enum or a struct somehow? Because I really like the convenience of it in addition to the simplification it offers in terms of code readability and writability.
C++ is not my strength as I don't use it that often and I never go deep in it whenever I do use it, and this is deeper than I currently understand where C++ is concerned.