如何为这种情况编写赋值运算符

How to write an assignment operator for this case?

本文关键字:赋值运算符 情况      更新时间:2023-10-16

我有一些代码在 MSVC 上编译得很好,但现在我正在将其移植到 Clang,并且在编写赋值运算符时遇到问题,我猜它被认为是 MSVC 中隐含的。这是我得到的代码:

enum EBufferPacking {
    Invalid = -1, UInt1, Int8, Int16, Float32
};
template<EBufferPacking p>
class PackedBufferRef;
template<>
class PackedBufferRef<UInt1> {
    unsigned char *const m_pBuffer;
    const unsigned char m_nMask; 
public:
    explicit PackedBufferRef<UInt1>(void *buffer, int offset):
        m_pBuffer((unsigned char *)buffer + offset/8),
        m_nMask(1<<(offset%8))
    {}
    operator float() const
    {
        return (*m_pBuffer & m_nMask) ? 1.0f : 0.0f;
    }
    template<class T>
    PackedBufferRef<UInt1> &operator =(const T &t)
    {
        if (!t) // write 0
            *m_pBuffer &= ~m_nMask;
        else
            *m_pBuffer |=  m_nMask;
        return *this;
    }
    PackedBufferRef<UInt1> &operator =(const PackedBufferRef<UInt1> &ref)
    {
        if( !(*ref.m_pBuffer & ref.m_nMask) )
            *m_pBuffer &= ~m_nMask;
        else
            *m_pBuffer |=  m_nMask;
        return *this;
    }
};

template<class T>
class BytePackedBufferRef{
protected:
    T *const m_pBuffer; // dont assign new pointers
    BytePackedBufferRef<T>(void *buffer, int offset): m_pBuffer((T *)buffer + offset) {}
    BytePackedBufferRef &operator=(const BytePackedBufferRef &other) {
        // assignment operator should go here   
    }
public:
    operator T*() const { return m_pBuffer; }
    operator T() const { return *m_pBuffer; }
};
template<>
class PackedBufferRef<Float32>:public BytePackedBufferRef<float> {
public:
    explicit PackedBufferRef<Float32>(void *buffer, int offset):BytePackedBufferRef<float>(buffer, offset) {}
    template<class T> PackedBufferRef<Float32> &operator =(const T &t) { *m_pBuffer = (float)t; return *this; }
};
int main()
{
    float fx = 0.5f;
    float fy = 1.7f;
    PackedBufferRef<Float32> firstRef(&fx, 0);
    PackedBufferRef<Float32> secondRef(&fy, 0);
    firstRef = secondRef;
    printf("First ref: %.2fn", (float)firstRef);
    printf("Second ref: %.2fn", (float)secondRef);
    return 0;
}

从 main 函数中,您可以看到我要得到的结果:我想从赋值的 RHS 上的变量中获取m_pBuffer,并将其放入 LHS 变量的m_pBuffer中。PackedBufferRef 专用化有一个执行此操作的赋值运算符,但它只是将赋值传递给BytePackedBufferRef类型,其m_pBuffer成员被声明为 const。在这种情况下,我该如何编写赋值运算符?

如果你坚持,你可以这样做......

BytePackedBufferRef &operator=(const BytePackedBufferRef &other) {
    // assignment operator should go here 
    T** pp = (T**)&m_pBuffer;
    *pp = other.m_pBuffer;  
}