user1229788
user1229788

Reputation:

Overloading Operators with templates

So I'm having issues overloading the assignment operator when working with templates. Basically, I'm taking a custom resizable array class, and that's being inherited by a different array class that lacks the ability to be resized. Anyway, I have two equality operators, one for dealing with arrays of the same size, and one for dealing with arrays of different sizes, so long as the type is the same.

Here's the code for the operators:

// operator =
//
template <typename T, size_t N>
const Fixed_Array <T, N> & Fixed_Array <T, N>::operator = (const Fixed_Array <T, N> & rhs)
{
    for(size_t x = 0; x < N; x++)
    {
        this->set(x, rhs[x]);
    }
    return *this;
}

//
// operator =
//
template <typename T, size_t N>
template <size_t M>
const Fixed_Array <T, N> & Fixed_Array <T, N>::operator = (const Fixed_Array <T, M> & rhs)
{
    this->resize(M);
    for(size_t x = 0; x < M; x++)
    {
        this->set(x, rhs[x]);
    }
    return *this;
}

And here's what I'm using to create and assign:

    Fixed_Array<char, 10> * fa1 = new Fixed_Array<char, 10>();
    Fixed_Array<char, 20> * fa2 = new Fixed_Array<char, 20>();
fa1 = fa1; //works
fa1 = fa2; //causes compiler to freak out

The error message basically is saying that I can't do this with 10 and 20; it's not picking up my second assignment operator with the template .

Any suggestions?

Upvotes: 0

Views: 136

Answers (2)

Ben Voigt
Ben Voigt

Reputation: 283793

How are you calling resize on a class that is supposed to have fixed size? Won't that break things?

For example,

Fixed_Array<char, 10> little1;
Fixed_Array<char, 20> big1, big2;

big1 = little1;
/* now big1 has size 10, because it was resized */
big1 = big2; /* tries to store 20 elements into a buffer of size 10 */

This will corrupt the heap (formally, it's undefined behavior).

Upvotes: 0

iammilind
iammilind

Reputation: 70078

You are assigning a pointer and not the object (causing memory leak as a side effect !). The pointers are of different types (<char,10> and <char,20>), so compiler complains about it.

Your operator = signature seems correct, the syntax for assignment should be:

*fa1 = *fa2; // ok  (no memory leak)

Upvotes: 2

Related Questions