How can interface return an unknown type? - c++

I'm trying to make a cpp interface class (pure virtual) declare a function that all derived classes must implement. However because the interface class is trying to be ignorant of implementation details, it doesn't know about the type of the returned object, and would like to delegate that to the derived class. The specific type of the returned object is handled by the derived class.
class UIInterface
{
// Should not know about QWidget
// Would like to defer return type until derived class which implements interface
QWidget *getWindow() = 0;
}
class QUIManager : public UIInterface
{
QWidget *getWindow() override {return m_widget;}
}
class XUIManager : public UIInterface
{
XWidget *getWindow() override {return m_widget;}
}
Except UIInterface should not know about QWidget. In some future version, the UIManager might be an XUIManager which returns a different type of window. If possible, I'd like to avoid returning std::any or void * followed by casting.
This pattern keeps showing up in my code, so I'm probably doing something wrong.
Edit based on comments:
My code is experimental, so although I'm using Qt as the UI for now, it's conceivable that may change, for example to use an immediate mode package, or in any case to separate the core logic from the UI. The core logic, may, for example, be accessed from just a console with no UI. Likewise, I'm using Qt's model/view and database classes.
Some examples:
The core needs to tell the UI to open and close windows. I've concluded in most cases that the core does not need to blindly shuffle naked UI pointers, so perhaps this use case is no longer that important.
The core needs to be able to glue database, model, and view together, without these latter three items knowing about each other, even though all three latter items may be specific to Qt or some other framework, or split up, such as using sqlite3 standalone and delegating model/view to Qt. For example, core needs to tell database interface to open a sqlite3 file, ask the modelcreator to create a model based on this, then pass model to UIManager to create the view. In no case does the core need to know specific types, and it would probably suffice to pass pointers around, but this seems like it's not the C++ way these days.
Although for now the track is C++, at some point the core itself might be implemented in a language better suited to the core algorithmic functions, eg Julia, Common Lisp, etc., which will introduce an impedance mismatch with Qt, so I'm trying my best to ensure the core can blindly call some high level functions while still serving as the central hub for the application.

Two options come in my mind, depending what fit better in your project:
1) Use a placeholder for return type:
class UIInterface
{
Widget* getWindow() = 0;
}
you can define in other file using Widget = QWidget. You can hange the alias or even implement your class Widget later and the whole UIInterface will not change. In this case you're just hiding the real type to the layout of your class.
2) You shoulde use a template class like
template<typename T>
class UIInterface
{
T* getWindow() = 0;
}
BUT there are downsides for No.2: you cannot use anymore UIInterface as interface without specifying T, and you're actually to state thatQWidget is the concrete type for T in your code.
Since you wrote "the interface might change in future" and not "I would create an interface regardless of the concrete widget type" I guess the option that fit you better is No.1

Related

How to handle external arbitrary class-type handlers in GUI testing library?

I'm trying to invent a GUI testing library for Qt. The library is meant to work remotely, so that I can run tests on mobile devices over WiFi. It should simply provide API for visible element's functions.
It should be extensible. In Qt, any visible GUI element is subclass of QWidget. I can hard-code handling for QPushButton (eg. clicking) or QLineEdit (writing text) but note that user can define his or her own QWidget subclasses, some of which may represent completely new kind of GUI.
In Java, I could solve this because class type is essentially a variable of Class type. So I could have:
public static void registerTestingHandler(Class<? extends java.awt.Component> GUIObject, Class<? extends TestingApi> apiHandler) {
...
}
The TestingApi would then be some basic interface which would accept messages as strings, eg: handler.doAction("click");
C++ doesn't have this kind of reflection. I also learned that it's impossible to get class' constructor address which could be used for this purpose. I think the whole design should probably look different in C++.
Therefore the question is: How do I allow user to register abstract handlers for specific class instances?

Data abstraction that really allows isolating implementation from the user in C++

I hesitate to ask this question, because it's deceitfully simple one. Except I fail to see a solution.
I recently made an attempt to write a simple program that would be somewhat oblivious to what engine renders its UI.
Everything looks great on paper, but in fact, theory did not get me far.
Assume my tool cares to have an IWindow with IContainer that hosts an ILabel and IButton. That's 4 UI elements. Abstacting each one of these is a trivial task. I can create each of these elements with Qt, Gtk, motif - you name it.
I understand that in order for implementation (say, QtWindow with QtContainer) to work, the abstraction (IWindow along with IContainer) have to work, too: IWindow needs to be able to accept IContainer as its child: That requires either that
I can add any of the UI elements to container, or
all the UI elements inherit from a single parent
That is theory which perfectly solves the abstraction issue. Practice (or implementation) is a whole other story. In order to make implementation to work along with abstraction - the way I see it I can either
pollute the abstraction with ugly calls exposing the implementation (or giving hints about it) - killing the concept of abstraction, or
add casting from the abstraction to something that the implementation understands (dynamic_cast<>()).
add a global map pool of ISomething instances to UI specific elements (map<IElement*, QtElement*>()) which would be somewhat like casting, except done by myself.
All of these look ugly. I fail to see other alternatives here - is this where data abstraction concept actually fails? Is casting the only alternative here?
Edit
I have spent some time trying to come up with optimal solution and it seems that this is something that just can't be simply done with C++. Not without casting, and not with templates as they are.
The solution that I eventually came up with (after messing a lot with interfaces and how these are defined) looks as follows:
1. There needs to be a parametrized base interface that defines the calls
The base interface (let's call it TContainerBase for Containers and TElementBase for elements) specifies methods that are expected to be implemented by containers or elements. That part is simple.
The definition would need to look something along these lines:
template <typename Parent>
class TElementBase : public Parent {
virtual void DoSomething() = 0;
};
template <typename Parent>
class TContainerBase : public Parent {
virtual void AddElement(TElementBase<Parent>* element) = 0;
};
2. There needs to be a template that specifies inheritance.
That is where the first stage of separation (engine vs ui) comes. At this point it just wouldn't matter what type of backend is driving the rendering. And here's the interesting part: as I think about it, the only language successfully implementing this is Java. The template would have to look something along these lines:
General:
template<typename Engine>
class TContainer : public TContainerBase<Parent> {
void AddElement(TElementBase<Parent>* element) {
// ...
}
};
template<typename Engine>
class TElement : public TElementBase<Parent> {
void DoSomething() {
// ...
}
};
3. UI needs to be able to accept just TContainers or TElements
that is, it would have to ignore what these elements derive from. That's the second stage of separation; after all everything it cares about is the TElementBase and TContainerBase interfaces. In Java that has been solved with introduction of question mark. In my case, I could simply use in my UI:
TContainer<?> some_container;
TElement<?> some_element;
container.AddElement(&element);
There's no issues with virtual function calls in vtable, as they are exactly where the compiler would expect them to be. The only issue would be here ensuring that the template parameters are same in both cases. Assuming the backend is a single library - that would work just fine.
The three above steps would allow me to write my code disregarding backend entirely (and safely), while backends could implement just about anything there was a need for.
I tried this approach and it turns to be pretty sane. The only limitation was the compiler. Instantiating class and casting them back and forth here is counter-intuitive, but, unfortunately, necessary, mostly because with template inheritance you can't extract just the base class itself, that is, you can't say any of:
class IContainerBase {};
template <typename Parent>
class TContainerBase : public (IContainerBase : public Parent) {}
nor
class IContainerBase {};
template <typename Parent>
typedef class IContainerBase : public Parent TContainerBase;
(note that in all the above solutions it feels perfectly natural and sane just to rely on TElementBase and TContainerBase - and the generated code works perfectly fine if you cast TElementBase<Foo> to TElementBase<Bar> - so it's just language limitation).
Anyway, these final statements (typedef of class A inheriting from B and class X having base class A inheriting from B) are just rubbish in C++ (and would make the language harder than it already is), hence the only way out is to follow one of the supplied solutions, which I'm very grateful for.
Thank you for all help.
You're trying to use Object Orientation here. OO has a particular method of achieving generic code: by type erasure. The IWindow base class interface erases the exact type, which in your example would be a QtWindow. In C++ you can get back some erased type information via RTTI, i.e. dynamic_cast.
However, in C++ you can also use templates. Don't implement IWindow and QtWindow, but implement Window<Qt>. This allows you to state that Container<Foo> accepts a Window<Foo> for any possible Foo window library. The compiler will enforce this.
If I understand your question correctly, this is the kind of situation the Abstract Factory Pattern is intended to address.
The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the theme. The client doesn't know (or care) which concrete objects it gets from each of these internal factories, since it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.
Creating a wrapper capable of abstracting libraries like Qt and Gtk doesn't seems a trivial tasks to me. But talking more generally about your design problem, maybe you could use templates to do the mapping between the abstract interface and a specific implementation. For example:
Abstract interface IWidget.h
template<typename BackendT>
class IWidget
{
public:
void doSomething()
{
backend.doSomething();
}
private:
BackendT backend;
};
Qt implementation QtWidget.h:
class QtWidget
{
public:
void doSomething()
{
// qt specifics here
cout << "qt widget" << endl;
}
};
Gtk implementation GtkWidget.h:
class GtkWidget
{
public:
void doSomething()
{
// gtk specifics here
cout << "gtk widget" << endl;
}
};
Qt backend QtBackend.h:
#include "QtWidget.h"
// include all the other gtk classes you implemented...
#include "IWidget.h"
typedef IWidget<QtWidget> Widget;
// map all the other classes...
Gtk backend GtkBackend.h:
#include "GtkWidget.h"
// include all the other gtk classes you implemented...
#include "IWidget.h"
typedef IWidget<GtkWidget> Widget;
// map all the other classes...
Application:
// Choose the backend here:
#include "QtBackend.h"
int main()
{
Widget* w = new Widget();
w->doSomething();
return 0;
}

Qt5 and Pattern for similar dialogs implementation

What is in your opinion the best way to implement similar dialogs in Qt5 without duplicating the code?
This is the problem: having two "slightly different" data structures, with many common parts, implement two "slightly different" QDialog to handle the user interaction.
We have two structures:
class DataA {
public:
int one, two, three;
bool x,y;
SubdataA subA;
}
class DataB {
public:
int one, two, three;
bool x,y;
SubdataB subB;
}
SubdataX is some other structured data we need to handle in the GUI. The two QDialog should handle the common fields the same way, while SubdataX must be handled by specific parts. The code should also make some operation on the data structures, and provide output files. This part is quite easy.
My question is, what are the best strategies to implement this? The objective is to have elegant code that should be quite easy to maintain and as most readable as possible. The framework is Qt, so the solution should be tailored to Qt with qdialog layout in UI files, since the gui layout is too complex to design it by code.
Thank you.
I'm not sure what you mean by "difficult to manage the ancestor class". I think I understand you want a polymorphic input to determine the layout of a dialog box. Is this assumption correct?
For example, given the following classes, you're able to use a dynamic cast to influence the behaviour of a dialog box.
class IData {
public;
int one, two, three;
bool x, y;
};
class DataA : public IData {
public:
// more data in here
};
class DataB : public IData {
public:
// more unique data in here
}
Now, assume you have written a dialog box with a function signature
void configureDialog(IData *data) {
DataA *dataA = dynamic_cast<DataA*>(data);
if (dataA) {
// configure what parts of the QDialog to see here
}
DataB *dataB = dynamic_cast<DataB*>(data);
if (dataB) {
// configure other parts of the QDialog you want to see
}
}
Which would allow for polymorphic configuration of a single QDialog box.
As Tyler Jandreau stated, a possible solution is to use polymorphism.
But this requires a careful planning of architecture and class inheritance, because to avoid using downcasting and a huge and unmaintenable number of switch() cases, you need also to use polymorphism on the GUI classes.
As View/Model architecture requires, the data classes will be mimicked by the control/Gui classes.
Data classes will be implemented using an ancestor, abstract class CommonData that includes the common "fields", and two (or more) concrete data classes derived from CommonData through inheritance. My first idea was to use composition instead, but this would pose other issues when implementing the gui.
So DataA and DataB are derived from CommonData.
On the Gui side, the structure is similar, but due to lack of inheritance support of the UI form classes generated by Qt's uic, we cannot use inheritance. My first guess was to use Template Metaprogramming, and implement the ancestor class as a Template class, but though it worked on the C++ side, moc refuses to parse that class and generate the moc_X file when the Q_OBJECT tagged class is a template.
So we are going to use a mix of inheritance and composition.
This is the architecture: a "container" GUI class (ContainerDialog) implements the GUI for the CommonData class; a PluggableInterface abstract class will define a set of operation (we'll see which below); a set of concrete classes derived from the latter will implement the GUI logic for the remaining classes.
So the ContainerDialog loads a ContainerDialog.ui form as a "standard" QDialog, and manages all the interface with CommonData. His constructor , or a setter will receive a CommonData pointer, remember that CommonData is abstract and cannot be instantiated.
The specific fields are managed thorugh specific graphic components that are "plugged" in the ContainerDialog gui. For example, a method defined in PluggableInterface will insert the QWidget derived component in the ContainerDialog gui. The classes involved are, for example, ComponentA1, ComponentA2, ComponentB, etc...
The use of the abstract interface PluggableInterface and the UI components will prevent the ContainerDialog to know what kind of concrete class are in use, and all the necessary code to instantiate the specific classes can be implemented using some creational pattern (Abstract Factory, Prototypes, etc...)

Is creating a base class for all applications of a particular type good design?

I am trying to write a graphics application in C++. It currently uses OGRE for display, but I'd like it to work with Irrlicht or any other engine, even a custom rendering engine which supports my needs. This is a rather long question, so I'd appreciate help on re-tagging/ cleanup (if necessary). I'll start with a little background.
The application has three major states:
1. Display rasterized scene
2. Display a ray traced version of the same scene
3. Display a hybrid version of the scene
Clearly, I can divide my application into four major parts:
1. A state management system to switch between the above modes.
2. An input system that can receive both keyboard and mouse input.
3. The raster engine used for display.
4. The ray tracing system.
Any application encompassing the above needs to be able to:
1. Create a window.
2. Do all the steps needed to allow rendering in that window.
3. Initialize the input system.
4. Initialize the state manager.
5. Start looping (and rendering!).
I want to be able to change the rendering engine/state manager/input system/ ray tracing system at any time, so long as certain minimum requirements are met. Imho, this requires separating the interface from the implementation. With that in mind, I created the interfaces for the above systems.
At that point, I noticed that the application has a common 'interface' as well. So I thought to abstract it out into an ApplicationBase class with virtual methods. A specific application, such as one which uses OGRE for window creation, rendering etc would derive from this class and implement it.
My first question is - is it a good idea to design like this?
Here is the code for the base class:
#ifndef APPLICATION_H
#define APPLICATION_H
namespace Hybrid
{
//Forward declarations
class StateManager;
class InputSystem;
//Base Class for all my apps using hybrid rendering.
class Application
{
private:
StateManager* state_manager;
InputSystem* input_system;
public:
Application()
{
try
{
//Create the state manager
initialise_state_manager();
//Create the input system
initialise_input_system();
}
catch(...) //Change this later
{
//Throw another exception
}
}
~Application()
{
delete state_manager;
delete input_system;
}
//If one of these fails, it throws an
//exception.
virtual void initialise_state_manager() = 0;
virtual void initialise_input_system() = 0;
virtual void create_window() = 0;
//Other methods.
};
#endif
When I use OGRE, I rely on OGRE to create the window. This requires OGRE to be initialised before the createWindow() function is called in my derived class. Of course, as it is, createWindow is going to be called first! That leaves me with the following options:
1. Leave the base class constructor empty.
2. In the derived class implementation, make initialising OGRE part of the createWindow function.
3. Add an initialize render system pure virtual function to my base class. This runs the risk of forcing a dummy implementation in derived classes which have no use for such a method.
My second question is- what are your recommendations on the choice of one of these strategies for initialising OGRE?
You are mixing two unrelated functions in one class here. First, it serves as a syntactic shortcut for declaring and initializing StateManager and InputSystem members. Second, it declares abstract create_window function.
If you think there should be a common interface - write an interface (pure abstract class).
Additionally, write something like OgreManager self-contained class with initialization (looping etc) methods and event callbacks. Since applications could create and initialize this object at any moment, your second question is solved automatically.
Your design may save a few lines of code for creating new application objects, but the price is maintaining soup-like master object with potentially long inheritance line.
Use interfaces and callbacks.
P.S.: not to mention that calling virtual functions in constructor doesn't mean what you probably expect.
Yes, that is a good design, and it is one that I use myself.
For your second question, I would remove anything from the base constructor that has any possibility of not being applicable to a derived class. If OGRE wants to create the window itself then you need to allow it to do that, and I don't think that it makes sense to initialize OGRE in createWindow (it's misleading).
You could add an initialize render system virtual method, but I think you should just leave that task to the derived class's constructor. Application initialization is always a tricky task, and really, really difficult to abstract. From my experience, it's best not to make any assumptions about what the derived class might want to do, and just let it do the work itself in any way that it wants.
That said, if you can think of something that will absolutely apply to any conceivable derived class then feel free to add that to the base constructor.

Overriding / modifying C++ classes using DLLs

I have a project with a large codebase (>200,000 lines of code) I maintain ("The core").
Currently, this core has a scripting engine that consists of hooks and a script manager class that calls all hooked functions (that registered via DLL) as they occur. To be quite honest I don't know how exactly it works, since the core is mostly undocumented and spans several years and a magnitude of developers (who are, of course, absent). An example of the current scripting engine is:
void OnMapLoad(uint32 MapID)
{
if (MapID == 1234)
{
printf("Map 1234 has been loaded");
}
}
void SetupOnMapLoad(ScriptMgr *mgr)
{
mgr->register_hook(HOOK_ON_MAP_LOAD, (void*)&OnMapLoad);
}
A supplemental file named setup.cpp calls SetupOnMapLoad with the core's ScriptMgr.
This method is not what I'm looking for. To me, the perfect scripting engine would be one that will allow me to override core class methods. I want to be able to create classes that inherit from core classes and extend on them, like so:
// In the core:
class Map
{
uint32 m_mapid;
void Load();
//...
}
// In the script:
class ExtendedMap : Map
{
void Load()
{
if (m_mapid == 1234)
printf("Map 1234 has been loaded");
Map::Load();
}
}
And then I want every instance of Map in both the core and scripts to actually be an instance of ExtendedMap.
Is that possible? How?
The inheritance is possible. I don't see a solution for replacing the instances of Map with instances of ExtendedMap.
Normally, you could do that if you had a factory class or function, that is always used to create a Map object, but this is a matter of existing (or inexistent) design.
The only solution I see is to search in the code for instantiations and try to replace them by hand. This is a risky one, because you might miss some of them, and it might be that some of the instantiations are not in the source code available to you (e.g. in that old DLL).
Later edit
This method overriding also has a side effect in case of using it in a polymorphic way.
Example:
Map* pMyMap = new ExtendedMap;
pMyMap->Load(); // This will call Map::Load, and not ExtendedMap::Load.
This sounds like a textbook case for the "Decorator" design pattern.
Although it's possible, it's quite dangerous: the system should be open for extension (i.e. hooks), but closed for change (i.e. overriding/redefining). When inheriting like that, you can't anticipate the behaviour your client code is going to show. As you see in your example, client code must remember to call the superclass' method, which it won't :)
An option would be to create a non-virtual interface: an abstract base class that has some template methods that call pure virtual functions. These must be defined by subclasses.
If you want no core Map's to be created, the script should give the core a factory to create Map descendants.
If my experience with similar systems is applicable to your situation, there are several hooks registered. So basing a solution on the pattern abstract factory will not really work. Your system is near of the pattern observer, and that's what I'd use. You create one base class with all the possible hooks as virtual members (or several one with related hooks if the hooks are numerous). Instead of registering hooks one by one, you register one object, of a type descendant of the class with the needed override. The object can have state, and replace advantageously the void* user data fields that such callbacks system have commonly.