I’ve got some code that compiled fine on MSVC but now I’m porting it to Clang and having trouble with writing an assignment operator that I’m guessing was taken as implicit in MSVC. Here is the code I’ve got:
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;
}
From the main function you can see the result I’m going for: I want to take the m_pBuffer from the variable on the RHS of the assignment, and put it into the m_pBuffer on the LHS variable. The PackedBufferRef specialisation has an assignment operator that does this, but that just passes the assignment up to the BytePackedBufferRef type, whose m_pBuffer member is declared const. How can I go about writing an assignment operator in this case?
If you insist, you can do it like this…