copy assignment for different length

H

Hans

Hi All,

How do I change the copy assignment header as shown below to allow for
different array length?

bool_vector& operator= (const bool_vector& t)

Thanks,
Hans.

template<int len>
class bool_vector {
private:
bool *v;
int i;
int sz;
public:
bool_vector() {
v=new bool[sz=len];
for (i=0; i<sz; i++) v=0;
};
~bool_vector() {
delete [] v;
};
bool_vector& operator= (const bool_vector& t) {
cout << "rhs=" << sz << " lhz=" << t.sz;
if (this != &t) {
delete[] v;
v=new bool[sz]; // sz=t.sz
for (i=0;i<sz;i++) if (i<t.sz) v=t.v; else v=0;
};
return *this;
}
};

int main()
{
bool_vector<4> a,b;
bool_vector<5> c;
a=b;
//c=b; // fails
}
 
F

Frederick Gotham

Hans posted:
Hi All,

How do I change the copy assignment header as shown below to allow for
different array length?

bool_vector& operator= (const bool_vector& t)


template<int i>
bool_vector<i> &operator=(const bool_vector<i> &t);
 
R

Ron Natalie

Hans said:
Hi All,

How do I change the copy assignment header as shown below to allow for
different array length?
It's not a copy assignment operator because bool_vector<4>
is a DIFFERENT TYPE then bool_vector<5>. It's not clear
why you even use the size as a typed arg to the vector as
it seems nothing in your class really needs to be a template.
You don't even treat the length as constant.

I don't know what you want to do with differing sized arrays
but to allow assignemnt from one to another you'll have to
template an operator= on the additional type:

template <class R> bool_vector& operator=(const bool_vector<R>&() {
...


By the way, your class needs a copy constructor.
 
H

Hans

Ron Natalie said:
It's not a copy assignment operator because bool_vector<4>
is a DIFFERENT TYPE then bool_vector<5>. It's not clear
why you even use the size as a typed arg to the vector as
it seems nothing in your class really needs to be a template.

Because I am a beginner :)

I understand my error, the length should be handled in the constructor and
not with a template. I changed the code and now the assignment c=b works
fine.

Thanks,
Hans
 

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,781
Messages
2,569,615
Members
45,293
Latest member
Hue Tran

Latest Threads

Top