dimanche 10 avril 2016

template design pattern c++

I have a big problem in C++, I don't know the workaround/design pattern for this problem:

someclass.h

#ifndef SOMECLASS_H
#define SOMECLASS_H
#include <QString>
#include <QObject>

class SomeClass : public QObject
{
public:
    QString name = "";

    SomeClass() {}
};

#endif // SOMECLASS_H

someotherclass.h

#ifndef SOMEOTHERCLASS_H
#define SOMEOTHERCLASS_H
#include <QObject>
class SomeOtherClass : public QObject
{
public:
    SomeOtherClass() {}
};

#endif // SOMEOTHERCLASS_H

form.h

#ifndef FORM_H
#define FORM_H
#include "someclass.h"
#include "someotherclass.h"
#include <QDebug>

template <class T>
class Form
{
public:
    Form(T* objName)
    {
        if (QString(T::staticMetaObject.className()) == QString(SomeClass::staticMetaObject.className())) {
            funcName(objName);
        }
    }

    void funcName(SomeClass* obj)
    {
        // ... much code

        qDebug() << obj->name;

        // ... much code
    }
};

#endif // FORM_H

mainwindow.h

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "form.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();

    Form<SomeClass>* form;
    Form<SomeOtherClass>* form1;
    SomeClass* someClass;
    SomeOtherClass* someOtherClass;

private:
    Ui::MainWindow *ui;
};

#endif // MAINWINDOW_H

mainwindow.cpp

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    someClass = new SomeClass;
    someOtherClass = new SomeOtherClass;
    form = new Form<SomeClass>(someClass);
    form1 = new Form<SomeOtherClass>(someOtherClass);
}

MainWindow::~MainWindow()
{
    delete ui;
}

When i make form = new Form<SomeClass>(someClass); everything is ok. But when i make form1 = new Form<SomeOtherClass>(someOtherClass); I get an error.

no matching function for call to 'Form<SomeOtherClass>::funcName(SomeOtherClass*&)'
             funcName(objName);
                             ^

I cannot solve this with derived classes by overriding the function funcName(), cause there is so much code around the if-condition in the function, that I cannot write 10 times or so.

thank you for helping me

Aucun commentaire:

Enregistrer un commentaire