我期待为C ++中的任何类型实现主/从寄存器模型模板。我开始时:
template <typename T>
struct Reg {
Reg() {}
Reg& operator = (const T& d) {
this->d = d;
return *this;
}
Reg& operator = (const Reg& r) {
d = r.q;
return *this;
}
operator T& () {
return q;
}
void update() {
q = d;
}
T d; /** input */
T q; /** output */
};
在为Reg实例赋值时,想法是写入d
,但是当从Reg实例中读取时,想法是从q
读取任何类型T,无论是内在还是用户定义的类。
当使用例如T
= int
时,它可以正常工作,但是当使用用户定义类型的T
时,例如std:complex,它会失败。
Reg<int> a;
a = a + a; // work fine
Reg<complex<int> > b;
b = b + b; // no match for ‘operator+’ in ‘b + b’
我希望编译器在Reg::operator T&
之前选择complex<int>::operator +
,与T
= int
一样。第一个解决方案是在Reg中编写所有C ++运算符,将它们转发到d
。有更好的解决方案吗?
Reg<complex<int> > rc1;
complex<int> c2;
rc1 + c2; // work fine
c2 + rc1; // no match for ‘operator+’ in complex<int>
是否有一般解决方案将应用于Reg实例的所有运算符(在读取模式下)转发到d
对象,并在进行操作时将Reg实例自动转换为d
类型d
类型对象?
使用C ++ 11的解决方案也考虑到了:)