[SOLVED] Template functions



  • 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!



  • Hi,

    as the classes seem to be QObject / QWidget deribved, you can't use templates.



  • Any other way to streamline the process?


  • Moderators

    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.



  • 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!



  • 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...



  • Thank you, I will look into it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.