我想添加一个运算符覆盖来执行内联赋值/__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)
最佳答案
您可以从模板结构派生,而不是覆盖“->”和“=”运算符。
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
};
关于c++ - 具有重写运算符的模板类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1874061/