简体   繁体   中英

Overloading operator= in templated class

I am learning templates, and stumbled upon this issue:

template <typename T, typename CONT>
class someContainer {
public:
    someContainer (const std::initializer_list<T>& ini) {
        for (const auto& elem : ini) {
            m_cont.push_back(elem);
        }
    }

    template <typename DST_CONT>
    someContainer& operator=(const DST_CONT& cont) {
        m_cont.clear();
        for (const auto& elem : cont.m_cont) {
            m_cont.push_back(static_cast<T>(elem));
        }
        return *this;
    }
private:
    CONT m_cont;
}

If I call this class like this:

someContainer <int, std::vector<int>> ivec{ 1,2 };
someContainer <int, std::vector<int>> ivec2{ 1,2,3 };
ivec = ivec2;

Here m_cont will be correctly assigned with correct values by 1,2,3

But, If I do this:

someContainer <int, std::vector<int>> ivec{ 1,2 };
someContainer <int, std::deque<int>> ivec2{ 1,2,3 };
ivec = ivec2;

Assignment operation will fail with:

cannot access private member declared in class 'someContainer<int,std::deque<int,std::allocator<_Ty>>>'

How to achieve overloading operator= in this case, for example, assign template int, std::vector to float,std::deque?

Compiler is MSVC2015

Tried to make function as friend - but in friend function it is not possible to return *this.

Tried to make this function non-member - MSVC told that I can't make operator= non-member

First off, don't overload the assignment for just anything, but only for other specializations of the same template. Second, make all specializations friend s of each other:

template <typename T>
class X
{
    T m_;

    template <typename> friend class X;  // all specializations of X are friends

public:
    template <typename U>
    X & operator=(const X<U> & rhs)      // assign from any specialization of X
    {
        m_ = rhs.m_;
        return *this;
    }
};

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