C ++主/从寄存器模型

时间:2013-09-30 21:14:14

标签: c++ c++11 operators forwarding

我期待为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的解决方案也考虑到了:)

0 个答案:

没有答案