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

时间:2012-11-14 10:16:31

标签: c++ templates visual-c++ clang assignment-operator

我有一些代码可以在MSVC上编译好但是现在我将它移植到Clang并且编写一个我猜的赋值操作符时遇到了麻烦。这是我得到的代码:

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函数中你可以看到我想要的结果:我想从赋值的RHS上的变量中取m_pBuffer,然后将它放到m_pBuffer上LHS变量。 PackedBufferRef专门化有一个赋值运算符,它执行此操作,但只是将赋值传递给BytePackedBufferRef类型,其m_pBuffer成员被声明为const。在这种情况下,如何编写赋值运算符?

1 个答案:

答案 0 :(得分:1)

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

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