0

我有一些在 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: %.2f\n", (float)firstRef);
    printf("Second ref: %.2f\n", (float)secondRef);

    return 0;
}

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

4

1 回答 1

1

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

BytePackedBufferRef &operator=(const BytePackedBufferRef &other) {
    // assignment operator should go here 
    T** pp = (T**)&m_pBuffer;
    *pp = other.m_pBuffer;  
}
于 2012-11-15T11:46:59.373 回答