简体   繁体   English

使用相同代码重载多个签名的赋值运算符?

[英]Overloading assignment operator with same code for multiple signatures?

Say I have a class C:假设我有一个 class C:

class C {
    int m_i { 0 };
};

Now this class can be used for non-volatile and volatile objects:现在这个 class 可以用于非易失性和易失性对象:

C x;
volatile C y;

I want to be able to assign volatile to non-volatile, non-volatile to volatile and non-volatile to non-volatile.我希望能够将易失性分配给非易失性,将非易失性分配给易失性,将非易失性分配给非易失性。 So I overload C's assignment operator:所以我重载了 C 的赋值运算符:

class C {
    int m_i { 0 };
public:
    void operator=(const volatile C& source) volatile {
        m_i = source.m_i;
    }

    void operator=(const C& source) {
        m_i = source.m_i;
    }
};

Can this be done in a DRY way, without repeating the code in the operator= functions?这可以以 DRY 方式完成,而无需重复operator=函数中的代码吗?

So after thinking about it for a while, this is the best solution I could come up with:因此,在考虑了一段时间后,这是我能想到的最佳解决方案:

class C {
    int m_i { 0 };

    void assignFrom(const volatile C& src, const bool volatileSrc = true, const bool volatileSelf = true) volatile {
        auto& nqSrc = volatileSrc ? src : const_cast<const C&>(src);
        auto& self = volatileSelf ? *this : *const_cast<C*>(this);
        self.m_i = nqSrc.m_i;
    }

public:
    void operator=(const C& src) volatile {
        // non-volatile to volatile assignment
        assignFrom(src, false);
    }

    C& operator=(const volatile C& src) {
        // volatile to non-volatile assignment
        assignFrom(src, true, false);
        return *this;
    }

    C& operator=(const C& src) {
        // non-volatile to non-volatile assignment
        assignFrom(src, false, false);
        return *this;
    }
};

I tested it and it seems to be working fine.我测试了它,它似乎工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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