Intentional template redundancy possible?

Hello,

I'm writing a class Vector3<T> to represent a threedimensional vector with elements of type T. I am doing this as a practice for C++ operator overloading. Turns out to contain some template lecture as well. :-)

I have typedefed some variants for my class like so:
1
2
3
typedef Vector3<float> Vector3f;
typedef Vector3<double> Vector3d;
typedef Vector3<long double> Vector3ld;

etc.

Now, I can even implicitly go from a Vector3f to a Vector3d using a type cast function template. However, the other way around requires an explicit cast and I am still on non C++11 here, so I write a function for it:
1
2
3
	template<typename V> Vector3<V> as() const {
		return Vector3<V>(V(this->x), V(this->y), V(this->z));
	}

Then I can write this:
Vector3i intVec = Vector3d(3.2, 5.4, 9.5).as<int>();
However, I'd much prefer if I could instead have the call look like this:
Vector3i intVec = Vector3d(3.2, 5.4, 9.5).as<Vector3i>();
Is it possible to do that?

Off-topic: Forum post preview function is failing me/shows garbage.
EDIT: Got "ERROR Invalid form (for-NT34)" from your board software on first try.
Last edited on
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
template < typename NUMERIC_TYPE > struct Vector3
{
    typedef NUMERIC_TYPE type ;
    
    template < typename T > Vector3( T a , T b, T c ) : x(a), y(b), z(c) {}
    
    template < typename T > operator Vector3<T>() const { return Vector3<T>(x,y,z) ; }
    
    template < typename OTHER_VECTOR > OTHER_VECTOR as() const 
    { return OTHER_VECTOR(x,y,z) ; } // can acees typename OTHER_VECTOR::type if needed
    
    NUMERIC_TYPE x ;
    NUMERIC_TYPE y ;
    NUMERIC_TYPE z ;
};

typedef Vector3<double> Vector3d;
typedef Vector3<float> Vector3f;
typedef Vector3<int> Vector3i;

int main()
{
    Vector3d dblVec(3.2, 5.4, 9.5) ;
    Vector3i intVec = dblVec ;
    
    intVec = dblVec.as<Vector3i>() ;
}

http://coliru.stacked-crooked.com/a/cd0516513aef1c2c
I was thinking the wrong way round. This is much simpler than anything I had tried to cook up. It's also a great example to show compile-time checking, since accessing OTHER_VECTOR::type can only work with OTHER_VECTOR being of a certain class, i.e. Vector3. It could still be any class which contains typedef of same name, but I think that's beyond sane chaos-control? Thanks!
Topic archived. No new replies allowed.