Let me consider that I have 4 bytes that describe some real system parameters. Suppose that could be interpreted as float, uint32_t and boolean. The main idea to store and process this variables together. Now I use one class that (very simplified) have array of 4 bytes, functions float toFloat()
, uint32_t toInt()
, bool toBool()
and parameter ID (which specifies storing value type). So I need one function T getValue()
which will be returning the value of correct type T
. So my question is: what is the most correct way to do so? Should I use templates, inheritance, its combination or something else?
You could use a std::variant
:
std::variant<float, uint32_t, bool> bytes(3.1415);
This seems like a perfect usecase for unions. The only thing amiss is that in a union you don't know which value type was stored. You could either attach the type information, for example allowing access to the union member with an accessor setting the type up, or if you have any other mean to know the type you could use that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With