Raphael Sauer
Raphael Sauer

Reputation: 740

Using template on a QWidget constructor

I have created a QWidget class that should take a template pointer as an input. Doing so with a method works fine, however when I try to use it on the QWidget's constructor I get an error. Here's the code:

#ifndef GADGET_H
#define GADGET_H

#include <QObject>


struct P2D {
    Q_GADGET
    Q_PROPERTY(P2D p2d READ getP2D )
    Q_PROPERTY(float m_x READ getX WRITE setX)
    Q_PROPERTY(float m_y READ getY WRITE setY)

    P2D getP2D() {return *this;}
    float getX() {return this->m_x;}
    void setX(float x) {this->m_x = x;}
    float getY() {return this->m_y;}
    void setY(float y) {this->m_y = y;}

public:
    float m_x;
    float m_y;
}; Q_DECLARE_METATYPE(P2D)

#endif

Main:

#include "mainwindow.h"
#include "gadget.h"

#include <QApplication>
#include <QDebug>
#include <QMetaObject>
#include <QMetaProperty>
#include <QVariant>
#include <QWidget>
#include "objectintrospector.h"

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    qRegisterMetaType<P2D>();
    P2D point;
    point.m_x = 10;
    point.m_y = 25;

    objectIntrospector *oi = new objectIntrospector(nullptr, "P2D", &point);
    oi->show();
    return a.exec();
}

QWidget:

#ifndef OBJECTINTROSPECTOR_H
#define OBJECTINTROSPECTOR_H

#include <QWidget>

class objectIntrospector : public QWidget
{
    Q_OBJECT
public:
    template <class T>objectIntrospector(QWidget *parent = nullptr, const char* typeName =  nullptr, T *ptr = nullptr);
    ~objectIntrospector();

private:
    Ui::objectIntrospector *ui;
};

I get the following error:

undefined reference to `objectIntrospector::objectIntrospector<P2D>(QWidget*, char const*, P2D*)'

Is there any way to solve this error? Thanks for your time.

Upvotes: 2

Views: 115

Answers (1)

Top-Master
Top-Master

Reputation: 8751

From comments:

Did you implement this function in your .cpp file?

I haven't. But...

Hmm... you should know that the only way to get rid of the issues is defining the functions body.

So, if you need it to be generic, define the body in the header as well (and the compiler will handle the rest); Something like:

template <class T>
objectIntrospector::objectIntrospector(QWidget *parent, const char* typeName, T *ptr)
{
    // Your logic here...
}

Upvotes: 1

Related Questions