简体   繁体   中英

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


}

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM