[SOLVED] Template functions
-
wrote on 6 Jul 2011, 19:13 last edited by
Hello C++ gurus!
I have some classes that have approximately the same functionality. However, the return type of the functions differ. Let me show you.
@#ifndef ENTSTA_H
#define ENTSTA_H#include "tests/ent/ent.h"
class EntSta : public Ent
{
Q_OBJECT
public:
static EntSta *Instance();protected:
explicit EntSta(QWidget *parent =0);private:
static EntSta *_instance;@with implementation
@#include "entsta.h"
EntSta *EntSta::_instance = 0;
EntSta *EntSta::Instance()
{
if (_instance == 0)
{
_instance = new EntSta;
}
return _instance;
}EntSta::EntSta(QWidget *parent):
Ent(parent)
{
}
@Now, look at the other classes:
@#ifndef ENTRAP_H
#define ENTRAP_H#include "tests/ent/ent.h"
class EntRap : public Ent
{
Q_OBJECT
public:
static EntRap *Instance();protected:
explicit EntRap(QWidget *parent = 0);signals:
public slots:
private:
static EntRap *_instance;};@
with implementation
#endif // ENTRAP_H
@#include "entrap.h"
EntRap *EntRap::_instance = 0;
EntRap *EntRap::Instance()
{
if (_instance == 0)
{
_instance = new EntRap;
}
return _instance;
}EntRap::EntRap(QWidget *parent) :
Ent(parent)
{
}
@Identical, except return types. Is there a way I could streamline these classes? I read about function templates a bit, but I don't understand how I could use them to solve my problem.
Thanks in advance!
-
wrote on 6 Jul 2011, 19:31 last edited by
Hi,
as the classes seem to be QObject / QWidget deribved, you can't use templates.
-
wrote on 6 Jul 2011, 19:32 last edited by
Any other way to streamline the process?
-
wrote on 6 Jul 2011, 19:40 last edited by
You could return a pointer to the base class. Or is this a problem because it is static? What are you trying to achieve?
Edit: Take it back. Sorry, is getting late.
-
wrote on 6 Jul 2011, 19:44 last edited by
I am using the Singleton design pattern from Design Patterns: Elements of Reusable Object-Oriented Software. Moreover, each of these classes is a factory that will instantiate objects in subclasses. Hence, I only want one factory to be instantiated.
Now, the Singleton pattern has the same structure for all classes. I just wanted to know if there was a way to promote code reuse.
Thanks!
-
wrote on 6 Jul 2011, 20:10 last edited by
you can use some tricks that MS uses in ATL:
multiple inheritance with templates that know their derived classes. It works but is a bit tricked...
-
wrote on 6 Jul 2011, 20:11 last edited by
Thank you, I will look into it.
1/7