type conversion w/ template

B

bluekite2000

I current have
template<typename T>
class Vector
{
....
Vector(const Vector& Vin)
{
....
}
...
}
int main(void)
{
Vector<double> V(5);
Vector<int> V1(V);//doesnt work
}

How would I solve this problem?
Thanx.
 
V

Victor Bazarov

I current have
template<typename T>
class Vector
{
...
Vector(const Vector& Vin)
{
...
}
..
}
int main(void)
{
Vector<double> V(5);
Vector<int> V1(V);//doesnt work
}

How would I solve this problem?

Take a look at constructing from a range of iterators.
The std::vector does it, so could your Vector. Essentially,
you need to define a constructor that would take two arguments,
and construct your vector (sorry, Vector) from them. Make that
constructor a member template:

template<typename T>
class Vector
{
...
template<typename Iterator> Vector(Iterator i1, Iterator i2)
{
storage = ???[std::distance(i1, i2)];
while (i1 != i2)
*storage++ = *it1++;
}
...

I know that it's not necessarily how you implemented your class
(ahem, template), but it should give you the idea.

V
 
I

Ian

I current have
template<typename T>
class Vector
{
...
Vector(const Vector& Vin)

This is shorthand for Vector(const Vector<T>& Vin), you can't use a
Vector<double> as it is a completely different class.

You could try a template constructor:

template <typename Other> Vector(const Vector<Other>& Vin).

This assumes Other can be converted to a T somehow, that bit's up to you.

Ian
 

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

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top