c++ - 在模板类中重载 operator=

标签 c++ templates operator-overloading

我正在学习模板,偶然发现了这个问题:

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;
}

如果我这样调用这个类:

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

这里 m_cont 会被 1,2,3 正确赋值

但是,如果我这样做:

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

赋值操作将失败:

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

如何在这种情况下实现重载operator=,例如将模板int、std::vector赋值给float、std::deque?

编译器是MSVC2015

尝试将函数设为友元 - 但在友元函数中无法返回 *this。

试图让这个函数成为非成员 - MSVC 告诉我不能让 operator= 成为非成员

最佳答案

首先,不要为任何事情重载赋值,而只为同一模板的其他特化重载。其次,使所有专业成为彼此的 friend :

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;
    }
};

关于c++ - 在模板类中重载 operator=,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34244491/

相关文章:

c++ - 当动态分配内存时,为什么我们需要复制构造函数?

templates - 在哪里可以下载使用 stringtemplate 的完整示例 java 项目?

c++ - 派生类中的成员新/删除重载有用吗?

c++ - enable_if 迭代器作为默认模板参数?

C++ operator new 重载,编译错误

c++ - Clang 和 g++ 对运算符重载的处理方式不同?

c++ - 如何在 Windows 上链接动态构建的 cmake 文件?

c++ - GLFW/GLEW C++ (atioglxx.dll)

c++ - 将图像分割成单元格 QML/QT

C++ typedef 修复模板参数