如何为这种情况编写赋值运算符
How to write an assignment operator for this case?
我有一些代码在 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;
}
相关文章:
- 重载Singly Linked List中的赋值运算符
- 使用赋值运算符重载从类中返回jobject
- 标准库类型的赋值运算符的引用限定符
- 复制构造函数、赋值运算符C++
- 标准::变体的赋值运算符
- 移动赋值运算符;尝试引用已删除的函数.我该如何解决这个问题?
- 如何在不使用赋值运算符的情况下为动态变量赋值?
- 为什么我可以在不使用赋值运算符的情况下使用列表初始化普通数组
- 如何在没有复制赋值运算符的情况下交换两个对象
- 为什么在没有赋值运算符的情况下调用转换构造函数
- 如何为这种情况编写赋值运算符
- 为什么在这种情况下调用复制构造函数和赋值运算符
- 在这种情况下,我们需要禁用默认的复制构造函数和赋值运算符
- 如何在不重载赋值运算符的情况下运行此代码
- 为什么内存泄漏只发生在赋值运算符重载的情况下,而不是在复制构造函数中,以及复制和交换习惯用法如何解决它
- 在某些情况下,编写自己的复制构造函数而不是自己的赋值运算符是个好主意吗
- 如何在不使用赋值运算符的情况下为变量赋值
- 如何在没有复制构造函数和赋值运算符的情况下实例化实例变量
- 在不使用元素复制赋值运算符的情况下复制向量 - 可移植性
- 为什么在这种情况下不调用赋值运算符以支持复制构造函数