Downcasting without copying the whole thing

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#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;
}
Last edited on
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.
> You can't "convert" it to another type.
But you can treat it as you want.


Consider using free functions instead.
Topic archived. No new replies allowed.