PDA

View Full Version : how couild one simplify calling of same methods for different inherited classes.



acmezger
25th February 2013, 14:55
in my code using several qt widget classes I ses code like this:

} else if (caMenu *widget = qobject_cast<caMenu *>(w)) {
//qDebug() << "we have a menu";

if(data.edata.connected) {
// set no connection color
} else {
widget->setAlarmColors(NOTCONNECTED);
widget->setProperty("Connect", false);
}
widget->setAccessW(data.edata.accessW);

// choice ================================================== ================================================== ==============
} else if (caChoice *widget = qobject_cast<caChoice *>(w)) {
//qDebug() << "we have a choiceButton" << String << value;

if(data.edata.connected) {
// set no connection color
} else {
widget->setAlarmColors(NOTCONNECTED);
widget->setProperty("Connect", false);
}
widget->setAccessW(data.edata.accessW);

} else if .....



===============================
how could one call a routine using the same code with the same methods after dynamic casting ?

Santosh Reddy
25th February 2013, 15:20
You got it worng..

how couild one simplify calling of same methods for different inherited classes.
They not not same methods, they are two different methods each operating on a different TYPE (caMenu and caChoice). The thing common between them is they use the same logic / algorithm / techinique...

What you have is a compact form possible. The other way I can think of is have a template function somthing like


template <typename T>
bool isMyType<T>(QObject * object)
{
T * obj = qobject_cast<T *>(object);
return obj != 0;
}

acmezger
25th February 2013, 15:36
you are right, my phrasing was not correct. However I meant it your way.

How would you use the templating then in my example?

Santosh Reddy
25th February 2013, 15:49
if(isMyType<caMenu *>(w))
qDebug() << "we have a menu";
...
if(isMyType<caChoice *>(w))
qDebug() << "we have a choiceButton" << String << value;
...

acmezger
25th February 2013, 15:56
yes I understand the way you can test the type of the widget. However I do not see how I can then call the methods (widget->SetPropoerty) correctly casted and how the code is then simplified.

many thanks for your answers.

amleto
25th February 2013, 17:37
setAlarmColors
setProperty
setAccessW

what is the highest common class that has all of those methods? Lets say it is ClassX. If there isn't a common clsss then you should make an interface that does contain all the methods, then make all relevant classes inherit the interface (e.g. InterfaceX)
Then you just need one check:



if (ClassX *widget = qobject_cast<ClassX*>(w)) { // or InterfaceX
//qDebug() << "we have a ... not sure exactly what it is, but we know it has all the methods required...

if(data.edata.connected) {
// set no connection color
} else {
widget->setAlarmColors(NOTCONNECTED);
widget->setProperty("Connect", false);
}
widget->setAccessW(data.edata.accessW);