lo tolmencre
lo tolmencre

Reputation: 3954

overload assignment operator for template class

I am trying to overload operator=(), but I am getting error: no viable overloaded '='. But I don't understand why. What am I missing here? I tired following the answers in Overloading assignment operator in a class template that can cast to another template type but there people say to give the template arguments of the return type a new type... ? That leads to the compiler complaining about an unknown type for me.

template<typename T, typename P>
class SomeClass
{

public:

    SomeClass<T, P> operator=(SomeClass<T, P>& src)
    {
        if (this != &src)
        {
            vectorfield.resize(src.vectorfield.size());
            for (int i = 0; i < src.vectorfield.size(); ++i)
            {
                vectorfield[i] = src.vectorfield[i];
            }
        }
        return *this;
    }

private:

    std::vector<std::vector<std::string>> vectorfield;
};



template<typename SC>
class SomeOtherClass
{

public:

    typedef SC someclass_type;

    void func()
    {
       sc = someclass_type();
    }

private:
    someclass_type sc;
};


int main()
{

    typedef SomeClass<int, int> SCII;
    typedef SomeOtherClass<SCII> SOC_scii;

    SOC_scii soc_scii;
    soc_scii.func();


}

Upvotes: 0

Views: 1039

Answers (2)

Dimitrios Bouzas
Dimitrios Bouzas

Reputation: 42929

Just change your assignment operator's signature to:

SomeClass<T, P>& operator=(SomeClass<T, P> const &src)
               ^                           ^^^^^

You have to return by reference to allow assignment chaining as show below:

SomeClass<T, P> a, b, c;
a = b = c;

The input parameter must be of of const reference otherwise you won't be able to assign temporary objects.

Upvotes: 2

Bo Persson
Bo Persson

Reputation: 92351

To work with temporaries, like in

   sc = someclass_type();

the parameter to the assignment operator should be a const reference.

SomeClass<T, P>& operator=(const SomeClass<T, P>& src)
               ^           ^^^^^

The assignment operator also generally returns are reference to the assigned object (so it can be used in chained assignments like a = b = c;). Returning by value would create an additional copy, which we probably don't want.

Upvotes: 5

Related Questions