【发布时间】:2009-12-09 13:54:45
【问题描述】:
我想添加一个运算符覆盖来执行 assignments/__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
那么,有没有办法让上面的这条线起作用?
编辑: 就像在模板类中一样,我希望“这条线”作为“集合”执行。
编辑:
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 ?
上线工作:
如果 (HVPSUControl->a)
【问题讨论】:
-
你想要的行为是什么?
-
你真正想要做什么以及为什么错误让你感到惊讶
-
我希望“这条线”像模板类中的“集合”一样执行。
-
顺便说一句,“没有错误”,它只是没有“做任何事情”(它不通过模板=)
-
在我看来
operator->正在返回一个 T*,然后那里只有一个a。a可能被编译为operator->的参数,但我不明白你将如何使用它,因为它不是真正的变量或任何东西。