I want to store and retrieve different data types in one object. This will late be an interface to a database.
Basic types (char, short, int, float, double, ...) should go into a union to save storage space. In addition, I want to store std::string
and std::vector
. Storage is done by overloading the assignment operator, retrieval is done by conversion operator overloading. The code below is a stripped-down version working with int
, double
and std::string
.
While the int
and double
parts work fine, the std::string
part fails. I'm also not sure if the operator overloading is the most elegant way to get the data in and out. I'm restricted to C++11, so std::any
is not an option.
#include <string>
class mydata {
private:
enum {
TID_INT,
TID_DOUBLE,
TID_STRING
};
int m_type_id; // stores one of TID_xxx
// this object should be able to store int, double, std::string
union {
int m_int;
double m_double;
} m;
std::string m_string;
public:
// Default constructor
mydata() { m_type_id = 0; }
// Overloading the Assignment Operator
template <typename T>
const T &operator=(const T &v) {
if (typeid(v) == typeid(int)) {
m_type_id = TID_INT;
m.m_int = v;
} else if (typeid(v) == typeid(double)) {
m_type_id = TID_DOUBLE;
m.m_double = v;
} else if (typeid(v) == typeid(const char *)) {
m_type_id = TID_STRING;
// this fails -->
//m_string = std::string(v);
}
return v;
}
operator int() {
if (m_type_id == TID_INT)
return m.m_int;
else if (m_type_id == TID_DOUBLE)
return (int) m.m_double;
return 0; // maybe throw an exception here
}
operator double() {
if (m_type_id == TID_INT)
return (double)m.m_int;
else if (m_type_id == TID_DOUBLE)
return m.m_double;
return 0;
}
};
/*------------------------------------------------------------------*/
int main() {
mydata d1, d2, d3;
d1 = 123; // store an int
d2 = 456.789; // store a double
int i = d1;
i = d2;
double d = d1;
d = d2;
// this fails --->
// d3 = "Hello"; // store a string
return 1;
}
Aucun commentaire:
Enregistrer un commentaire