I'm new in C++ and I would like to know if we can accept any struct as our method parameter.
This is the case:
I have one class (let's say hw_manager) that interact with the hardware class (let's say hw_device1). Currently hw_manager will call the method of hw_device1 and the result of the method will be returned via the struct parameter (send the struct parameter as reference, and change the value of the referenced parameter).
In C++ code should be like this:
struct sSensorStatus {
unsigned char sensor1;
unsigned char sensor2;
};
bool checkSensorStatus(struct sSensorStatus &status) {
// Change the status here
}
Now, since the hardware is changed, I need to create a new class, let's say hw_device2 which has totally different operation.
struct sHardwareStatus {
unsigned char loader;
unsigned char transport;
unsigned char ejector;
unsigned char mouth;
};
bool checkHardwareStatus(struct sHardwareStatus &status) {
// Change the status here
}
Rather than changing the code in hw_manager (that will affect the code above this layer) I'm planning to implement an interface, let's say IHardware that has doAction method.
The idea is like this:
bool doAction(int cmdID, ????) {
// switch case cmdID
// based on the cmdID, type cast the ???? into the struct
}
What should I put in ???? to accept any kind of struct? Can I do this in C++?
Thanks
EDIT
Inside the hardware, I will also have another struct, so I don't think using template will be appropriate. Sorry for late clarification.
Simply use polymorphism. Create a basic class for all devices and pass a pointer or reference to it as argument to the method doAction.
EDIT(thanks to Koushik's comment to elyashiv`s answer):
Actually a way better solution is to make the method doAction a virtual method in the base class for all devices and not pass anything at all to it.
you could do this :
struct IHardware{virtual doAction() = 0;}
now inherit that in
struct sHardwareStatus : public IHardware
{/*implementation with implementation for doAction()*/
unsigned char loader;
unsigned char transport;
unsigned char ejector;
unsigned char mouth;
/*provide concrete definition for bool doAction() here*/
}
also for
srtuct sSensorStatus : public IHardware
{/*implementation with implementation for doAction()*/
unsigned char sensor1;
unsigned char sensor2;
/*provide concrete definition for bool doAction() here*/
}
now when you have a new hardware inherit from the interface and then write the struct for that class. i guess doAction() will be different for each Hardware.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With