0
votes

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

1

1 Answers

1
votes

First off, don't overload the assignment for just anything, but only for other specializations of the same template. Second, make all specializations friends 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;
    }
};