single function to accept different parameter types
-
Hi all -
I realize that's a terrible title for a post, but I'm not sure how else to describe it. My app features several models for various entities. One of the duties of my model is to accept change requests from QML and send the request out (via HTTP).
This all was working fine until I needed to subclass the elements of one of my models. Now, I have a QML component that invokes a routine in my model:
equipmentModel.sendPatchRequest(equipmentObject)
where equipmentObject can be one of many subclasses of the parent Equipment struct. But I don't know how to code the C++ routine to allow for various types to be passed in. Here's what I've got so far:
void EquipmentModel::sendPatchRequest(const Equipment &equipment) { // Vsp is a subclass of equipment. const Vsp &vsp = static_cast<const Vsp &>(equipment);
Unfortunately, my vsp object still only has properties of the parent class.
Is it possible to change my function signature so that it will accept various subclasses? The alternative (coding individual wrappers for each subclass) isn't very appealing.
Thanks...
-
One of my co-workers came up with this workaround:
// would entail one of these routines for each subclass, // but they would all do the exact same thing. void EquipmentModel::sendPatchRequest(const Vsp &equipment) { sendBaseRequest(equipment); } void EquipmentModel::sendBaseRequest(const Equipment &equipment) { if (m_qnrPatch == nullptr) { int i = getIndex(equipment.m_uuid); if (i == NOT_IN_LIST) { continue; } Equipment &listEntry = *(*m_list)[i]; equipment.addPatchFields(listEntry, qjo, rolesToKeys); // goes to subclass function. ...
It works. Unless someone comes up with a better idea, I'll close out this topic. Thanks for all the suggestions...
-
@mzimmers
You can test at runtime whether an object inherits a particular class viadynamic_cast<>()
, orqobject_cast<>()
if it'sQObject
-derived. These returnnullptr
. So you can goif ()
to test the class, and act differently for each type. Is this what you mean?Unfortunately, my vsp object still only has properties of the parent class.
Don't know what tbis means.
-
@JonB an attempt at a dynamic_cast throws a std::bad_cast error, and the app exits. I can trap with via try/catch, but I think we already know what we need to from these results.
What I was trying to say above was, the way I have this coded, there doesn't seem to be anything I can do to access any of the properties of the subclass that's actually being passed as the argument.
-
@mpergand said in single function to accept different parameter types:
create a template function
template<class T> sendPatchRequest(const T &equipment)This is a great idea, if I can do it. Unfortunately, my editor seems to be telling me that template functions and Q_INVOKABLE aren't compatible.
-
@mzimmers said in single function to accept different parameter types:
Unfortunately, my editor seems to be telling me that template functions and Q_INVOKABLE aren't compatible.
Ouch !
Anyway, subclassing is a better OOP solution IMO, because it's logical that each equipment has its own model.
Maybe you need to rethink the way your equipments is managed by adding some abstract layer to it.
I described this kind of thing in an older post HERE
Hope this can help you. -
@mpergand said in single function to accept different parameter types:
Anyway, subclassing is a better OOP solution IMO
Oh, I definitely do use subclassing; I just didn't show it in my snippet above.
switch (listEntry.m_category) { case EquipmentNS::CATEGORY_VSP: m_pEquipment = std::make_shared<Vsp>(); break; default: m_pEquipment = std::make_shared<Equipment>(); break; } m_pEquipment->addPatchFields(qjo, listEntry, rolesToKeys);
The problem is, I need access to my temporary object (the one that QML is passing to this function). I can't figure out a way to do this.
-
@mzimmers said in single function to accept different parameter types:
The problem is, I need access to my temporary object (the one that QML is passing to this function). I can't figure out a way to do this.
Sorry, I know nothing about QML, so I can't help you more in this area, I'm afraid.
-
@mpergand I don't think the solution to this is going to involve changing the QML code, though I did read something about problems with going from JS to C++ and messing up the vtables.
What I need is a way to treat the value passed in as a member of any subclass I choose.
-
@mzimmers said in single function to accept different parameter types:
an attempt at a dynamic_cast throws a std::bad_cast error, and the app exits
Can you show how you're doing this casting? If target type is a pointer you should not get std::bad_cast but a nullptr (see https://en.cppreference.com/w/cpp/language/dynamic_cast).
-
@mzimmers said in single function to accept different parameter types:
@JonB an attempt at a dynamic_cast throws a std::bad_cast error,
I have never heard of such behaviour. It is very worrying if
dynamic_cast
throws an error, it is supposed to be usable to detect whether an object is of a particular class at runtime, and sounds like it is what you are looking for. It is used "millions" of times in worldwide C++ code.Is the object/class you are testing to do with QML, or just Qt? I would not know if QML does some "funny" which could lead to this behaviour.
You can Google
dynamic_cast std::bad_cast
, I didn't totally understand what they are saying, something to do with a "reference type". I only know of using it with a pointer type (hencenullptr
if it fails). With a value type it would have no way of returning a "failure" result, so I guess it can only throw. Even if you have a reference type you wish to test, somehow, I imagine you can take its address:if (dynamic_cast<Bar *>(&foo_value_variable)) ...
. -
@JonB said in single function to accept different parameter types:
I have never heard of such behaviour
-
@jsulm
Yes, I know and read that. Like I (and you) said it won't happen on a pointer, and I have never useddyanmic_cast<>
on anything but a pointer:c) Otherwise, the runtime check fails. If the dynamic_cast is used on pointers, the null pointer value of type target-type is returned. If it was used on references, the exception std::bad_cast is thrown.
That's why I suggested how @mzimmers might test a pointer even if he starts with a value type (via
&variable
)..P.S.
I note thatqobject_cast<>()
avoids this by only accepting a pointer-type, no value types! -
@JonB said in single function to accept different parameter types:
I have never heard of such behaviour. It is very worrying if dynamic_cast throws an error, it is supposed to be usable to detect whether an object is of a particular class at runtime, and sounds like it is what you are looking for. It is used "millions" of times in worldwide C++ code.
I think it also throws an error when the project is compiled with
-fno-rtti
or/GR
respectivelyand at least MSVC only gives a warning during compile time and you know what people do with warnings ^^
-
@J-Hilk
I don't dispute that compilers may have options to enable it or not, e.g. disable RTTI. But the extract I quoted from cppreference abovec) Otherwise, the runtime check fails. If the dynamic_cast is used on pointers, the null pointer value of type target-type is returned. If it was used on references, the exception std::bad_cast is thrown.
says null pointer returned (if pointer, which is what I was discussing), I don't see it say "undefined behaviour depending on compiler". Just saying.
In any case, I suspect @mzimmers' case is just that a pointer should be passed instead of a value.
-
@jsulm here's my call. I'm including it as a pic so you can see the debugger's locals window.
Vsp is a subclass of Equipment, which is a struct with Q_GADGET enabled.
Is it possible that this error is due to the fact that equipment is being passed in as an argument from QML? I remember reading (but not fully understanding) somewhere about incompatibilities between JS and C++, and the use of emscripten to remedy it. Something about the vtables getting messed up.
EDIT:
I changed my function a bit:
void EquipmentModel::sendPatchRequest(const Equipment &equipment) { const Equipment *ePtr = &equipment; const Vsp *vsp = dynamic_cast<const Vsp *>(ePtr);
and this returned a null pointer as @JonB said it would. So, I guess the lesson is you can't use dynamic_cast to downcast references.
Good to know, but...I'm still stuck with how to fix this issue.
-
@mzimmers well, this works just fine and as expected:
#include <iostream> // Base class class Base { public: virtual ~Base() {} }; // Derived class class Derived : public Base { public: void sayHello() const { std::cout << "Hello from Derived class!" << std::endl; } }; // Function that takes a const reference to a Base object void func(const Base& base) { try { const Derived& derived = dynamic_cast<const Derived&>(base); derived.sayHello(); } catch (const std::bad_cast& e) { std::cout << "dynamic_cast failed with message: " << e.what() << std::endl; } } int main() { Derived d; func(d); // This will succeed Base b; func(b); // This will fail and catch block will execute }
Hello from Derived class!
dynamic_cast failed with message: std::bad_cast -
@J-Hilk yes, that works when the caller of func() is a C++ function. When it's coming from QML, I get the bad_cast error.
So, I guess this isn't a C++ problem after all; it does have something to do with the interaction between C++ and QML. I can post something to the QML forum about it.
-
@mzimmers
I really don't like the use of dynamic_cast here, seems unsafe.I definitely do use subclassing; I just didn't show it in my snippet above.
I didn't think about Equipment subclass, but EquipmentModel subclass, like:
void VspEquipmentModel::sendPatchRequest(const Vsp &vsp)
that way, each equipment model receives the right equipment is dealing with.
No more casting is needed. -
@mpergand that would be an option, but I'm going to have about 40 subclasses of Equipment. I'd really prefer not to have to make 40 subclasses of the model just for this purpose. Plus, I'd have to instantiate the subclass 40 times, with a lot of overhead.