我想添加一个操作符覆盖来执行赋值 / __ set__s内联。
模板: -
class CBase {
public :
static void SetupVmeInterface(CVmeInterface *in);
protected :
static CVmeInterface *pVmeInterface;
};
template <class T> class TCVmeAccess : public CBase {
public:
TCVmeAccess(int address);
T get()
{
unsigned long temp = pVmeInterface->ReadAddress(Address);
T ret = *reinterpret_cast<T*>(&temp);
return ret;
};
T *operator->();
unsigned long asLong();
bool set(T data)
{
unsigned long write_data = *reinterpret_cast<unsigned long*>(&data);
return pVmeInterface->WriteAddress(Address, write_data);
};
// void operator->(T);
void operator=(T data)
{ set(data); }
private :
int Address;
};
将在模板中使用的结构: -
typedef struct
{
int a: 1; // 0
int b: 1; // 1
int c: 1; // 2
int d: 1; // 3
int NotUsed : 28; // 31-4
} _HVPSUControl;
代码正文: -
TCVmeAccess<_HVPSUControl> HVPSUControl(constHVPSUControlBlock);
_HVPSUControl hvpsu = HVPSUControl.get(); // Yep, good, but not as nice as...
int a = HVPSUControl2.get().OperationalRequestPort; // yep, also good, but...
int b = HVPSUControl->a; // works, and is all go so far
HVPSUControl.set(hvpsu); // works, but need _HVPSUControl type
HVPSUControl = hvpsu; // also works, as operator = is used, but still need type
// this line does not work!
// as the = assignment is redirected into a copy of the struct, not the template
HVPSUControl->a = 1; // this line
那么,有没有办法让上面的这一行工作?
编辑: 在中,我希望“this line”作为“set”执行,就像在模板类中一样。
编辑:
1.直接在构造模板的结构的成员中直接分配值
的。
2.导致该分配通过模板访问器。
所以我不必在作业上这样做: -
// HVPSUControl is predefined and used many times.
_HVPSUControl hvpsu;
hvpsu.a = 1;
HVPSUControl.set(hvpsu);
我想做
HVPSUControl.a = 1; // or
HVPSUControl->a = 1; // or ?
随着上线工作:
if(HVPSUControl-&gt; a)
答案 0 :(得分:1)
而不是覆盖“ - &gt;”和“=”运算符,你可以从模板结构派生。
template <class T> class TCVmeAccess : public CBase, public T {
public:
TCVmeAccess(int address);
T get();
// T *operator->();
unsigned long asLong();
bool set(T);
// void operator->(T);
// void operator=(T);
private :
int Address;
};
HVPSUControl.a = 1; // and use this for setting a bitfield.
编辑:如果你想使用自定义赋值运算符,你应该在HVPSUControl或它的基类中声明它,如果你有更多这种类似控件的结构。
struct _HVPSUControl
{
int a: 1; // 0
int b: 1; // 1
int c: 1; // 2
int d: 1; // 3
int NotUsed : 28; // 31-4
void operator = (int x);
};
或
struct _HVPSUBase {
void operator = (int x);
}
struct _HVPSUControl: public _HVPSUBase
{
int a: 1; // 0
int b: 1; // 1
int c: 1; // 2
int d: 1; // 3
int NotUsed : 28; // 31-4
};
答案 1 :(得分:0)
你不能让这条线以任何其他方式工作。您致电TCVmeAccess::operator->
,返回_HVPSUControl*
,然后访问_HVPSUControl*::a
。
或者您想将整数1分配给完整的_HVPSUControl
结构?
template <class T> class TCVmeAccess : public CBase {
public:
// ...
void operator=(T data) { set(data); }
void operator=(int n) { operator=(T(n)); }
// ...
};
typedef struct
{
_HVPSUControl(int n) {
*this = reinterpret_cast<_HVPSUControl>(n);
}
int a: 1; // 0
int b: 1; // 1
int c: 1; // 2
int d: 1; // 3
int NotUsed : 28; // 31-4
} _HVPSUControl;
然后再做
HVPSUControl = 1;