I want to make a common general template which specifies all 3D math on 3D vectors and than specialize it for float (double) (called Vec3d ) and integers (called Vec3i). I want to do this without any reimplementation of the common code.
Somebody recommanded to do it by inheritance instead of specialization. But when I do I get this error:
main.cpp:34:12: error: could not convert ‘dR.Vec3d::<anonymous>.Vec3TYPE<TYPE>::operator*<double>(k)’ from ‘Vec3TYPE<double>’ to ‘Vec3d’
return dR * k; // there is the error
Code is like this (extracted the relevant part):
#include <math.h>
#include <cstdio>
// definition of general template
template <class TYPE>
class Vec3TYPE{
public:
union{
struct{ TYPE x,y,z; };
struct{ TYPE a,b,c; };
TYPE array[3];
};
inline void set( TYPE f ) { x=f; y=f; z=f; };
inline void set( TYPE fx, TYPE fy, TYPE fz ) { x=fx; y=fy; z=fz; };
inline void set( const Vec3TYPE& v ) { x=v.x; y=v.y; z=v.z; };
inline Vec3TYPE operator+ ( TYPE f ) const { Vec3TYPE vo; vo.x=x+f; vo.y=y+f; vo.z=z+f; return vo; };
inline Vec3TYPE operator* ( TYPE f ) const { Vec3TYPE vo; vo.x=x*f; vo.y=y*f; vo.z=z*f; return vo; };
inline Vec3TYPE operator+ ( const Vec3TYPE& vi ) const { Vec3TYPE vo; vo.x=x+vi.x; vo.y=y+vi.y; vo.z=z+vi.z; return vo; };
inline Vec3TYPE operator- ( const Vec3TYPE& vi ) const { Vec3TYPE vo; vo.x=x-vi.x; vo.y=y-vi.y; vo.z=z-vi.z; return vo; };
inline Vec3TYPE operator* ( const Vec3TYPE& vi ) const { Vec3TYPE vo; vo.x=x*vi.x; vo.y=y*vi.y; vo.z=z*vi.z; return vo; };
inline Vec3TYPE operator/ ( const Vec3TYPE& vi ) const { Vec3TYPE vo; vo.x=x/vi.x; vo.y=y/vi.y; vo.z=z/vi.z; return vo; };
};
// specialization
class Vec3i : public Vec3TYPE<int>{}; // int version
class Vec3d : public Vec3TYPE<double>{ // float version
public:
inline double norm ( ) const { return sqrt( x*x + y*y + z*z ); };
};
inline Vec3d getForce( Vec3d dR, double k ){
return dR * k; // there is the error
}
// main
int main(){
Vec3d a; a.set( 1.0, 2.0, 3.0 );
// this works
Vec3d b; b.set( a * 4.0 );
printf( " %f %f %f \n", b.x, b.y, b.z );
// this does not
Vec3d b_; b_.set( getForce( a, 4.0 ) );
printf( " %f %f %f \n", b.x, b.y, b.z );
}