I'm trying to provide a uniform interface for two similar types, one dealing with doubles and the other with floats.
class float_type { float_type() { /* does floaty stuff */ } float f(); }; class double_type { double_type() { /* does doubly stuff */ } double f(); }; I want to write a class that allocates one or the other depending on what the program needs to do. I'm perfectly fine with the result of float_type::f() being converted to double. In fact, it happens anyway. I tried to write it like this:
class union_type { bool is_double; char mem[ sizeof(double_type) > sizeof(float_type) ? sizeof(double_type) : sizeof(float_type) ]; public: float_or_double_value_reader(bool is_double) : is_double(is_double) { if (is_double) new(mem) double_type(); else new(mem) float_type(); } ~float_or_double_value_reader() { if (is_double) delete static_cast<double_type*>(mem); else delete static_cast< float_type*>(mem); } double f() { return (is_doubled ? static_cast<double_type*>(mem)->f() : static_cast< float_type*>(mem)->f() ); } }; But I get invalid static_cast from type 'char [128]' to type 'double_type'.
I know I could add a member pointers to point to what new returns, but that would be redundant, since I already know where mem is located, so I want to avoid that.
If I use reinterpret_cast instead, I get free(): invalid pointer: at runtime when the union_type is destroyed.
What's the appropriate method of casting here?
datasupposed to bemem? Anyway, when you use placement new, you don't usedeleteon the object, because that will try to deallocate memory. Instead, explicitly call the appropriate destructor (likereinterpret_cast<double_type*>(data)->~double_type();)dataismem. Apologies for inconsistency. Let me fix it.