Casting between different template classes

M

Mike Tyka

Hello,

I'd like to write a vector class using templates to be able to handle floats
and doubles.
I can't seem to find a way though to cast between the float type and the
double type
of the vector class. Is there a way of implementing the following
mini-example neatly ??

Thanks for any help,

Mike

//---------------------------------
template <class T>
class vector{
public:
T x,y;
vector(T xinit,T yinit){ x=xinit;y=yinit; }
void add(vector &v){
x += v.x;
y += v.y;
}
};

void main(){
vector <float> vector_float(2.0f,3.0f);
vector <float> vector2_float(2.0f,1.0f);
vector <double> vector_double(-1.0,3.0);

// this works of course:
vector_float.add(vector2_float);

// this throws a compile error: - how can something like this be achieved
?
vector_float.add(vector_double);
}


// the error thrown is:
/*
c:\coding\visc\mathtest\mathtest\main.cpp(26): error C2664: 'vector<T>::add'
: cannot convert parameter 1 from 'vector<T>' to 'vector<T> &'
with
[
T=float
]
and
[
T=double
]
and
[
T=float
]
*/
 
V

Victor Bazarov

Mike said:
I'd like to write a vector class using templates to be able to handle floats
and doubles.
I can't seem to find a way though to cast between the float type and the
double type
of the vector class. Is there a way of implementing the following
mini-example neatly ??

Thanks for any help,

Mike

//---------------------------------
template <class T>
class vector{
public:
T x,y;
vector(T xinit,T yinit){ x=xinit;y=yinit; }
void add(vector &v){
x += v.x;
y += v.y;
}

Add this function:

template<class U> void add(vector<U> const &vu) {
x += vu.x;
y += vu.y;
}

The "native" 'add' will be used for the same type of vector, and the
templated 'add' will be used for "foreign" vectors.
};

void main(){

'main' _always_ returns an int.
vector <float> vector_float(2.0f,3.0f);
vector <float> vector2_float(2.0f,1.0f);
vector <double> vector_double(-1.0,3.0);

// this works of course:
vector_float.add(vector2_float);

// this throws a compile error: - how can something like this be achieved
?
vector_float.add(vector_double);

You can define your 'add' as a template. See above.

Victor
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top