I have a non-virtual class (VectorT) with exactly the same data structure with its derived (Vector3).
Derived class has more function members (e.g. a 3d vector has cross product extra member).
the question:
Can I make the VectorT<3> to act like a Vector3?
I can "downcast" with a copy c'tor in Vector3 but this is a painful method because it copies all elements from VectorT to Vector3.
#include <array>
template<size_t S>
class VectorT : public std::array<double, S>{};
struct Vector3 : public VectorT<3>
{
Vector3() = default;
// Can I avoid copying? Both of them share exactly the same data structure for God shake :-)
// I only want to apply functions on the data structures
Vector3(const VectorT<3> &v) : VectorT<3>(v) {}
Vector3 operator^(const std::array<double, 3> &v) const { /*......*/ return Vector3(); }
};
int main()
{
VectorT<3> v;
Vector3 a,b;
b = static_cast<Vector3>(v) ^ a;
return 0;
}
The short answer is no. An object cannot change it's type at runtime. An object is either a Vector3 or it isn't. You can't "convert" it to another type. The only way to accomplish that is to copy it.
Though you might be able to get more creative with your inheritance hierarchy to where this is a nonissue.
PS: I really hope you're not abusing operator overloading.