How to do type convertion for template class?

A

Allen

For example, define vector class as following:

namespace blas {

template<class T> class vector {
....
inline vector<T> operator=()
{
vector<T> t(*this);
return t;
}
};

}

Now define two instances:

blas::vector<double> a;
a = ...;
blas::vector<std::complex<double>> b;
b = a;

When compile the codes, c++ compiler will tell operator = is not
overloaded for type std::complex.
How to solve it?
Thank you very much.

Allen
 
R

Rolf Magnus

Allen said:
For example, define vector class as following:

namespace blas {

template<class T> class vector {
...
inline vector<T> operator=()
{
vector<T> t(*this);
return t;
}

operator= needs an argument - the object to copy from. 'this' is actually
the object to copy _to_.
};

}

Now define two instances:

blas::vector<double> a;
a = ...;
blas::vector<std::complex<double>> b;
b = a;

When compile the codes, c++ compiler will tell operator = is not
overloaded for type std::complex.
How to solve it?

Well, you can make the operator= a template, too.

template<class T> class vector {
...
template<class U>
inline vector<T>& operator=(const vector<U>& rhs)
{
// do your copy operation
return *this;
}
};
 
A

Allen

operator= needs an argument - the object to copy from. 'this' is actually
the object to copy _to_.

Yes, I made a mistake here.
Well, you can make the operator= a template, too.

template<class T> class vector {
...
template<class U>
inline vector<T>& operator=(const vector<U>& rhs)
{
// do your copy operation
return *this;
}

};

It does work now. Thank you.
 

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,755
Messages
2,569,536
Members
45,014
Latest member
BiancaFix3

Latest Threads

Top