Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct C++ approach to store multi-type data

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?

like image 891
Stanislav Avatar asked Mar 03 '23 13:03

Stanislav


2 Answers

You could use a std::variant:

std::variant<float, uint32_t, bool> bytes(3.1415);
like image 89
Paul Evans Avatar answered Mar 06 '23 01:03

Paul Evans


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.

like image 25
g_bor Avatar answered Mar 06 '23 02:03

g_bor