Search code examples
c++templatesassignment-operator

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();


}

Solution

  • 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.