嵌套模板类调用模板函数

时间:2017-12-13 10:06:48

标签: c++ qt

这是我项目的简化代码。

首先我有一个模板类:

TempA

然后是两个类型TempBclass TempA : public QObject{ Q_OBJECT }; class TempB : public QObject{ Q_OBJECT };

A

来自B的两个课程Baseclass A : public Base<TempA>{ Q_OBJECT }; class B : public Base<TempB>{ public: B(){ A* a = new A; QVariant v = QVariant::fromValue(a); //This v is actually passed from QML QObject* aa = v.value<QObject*>(); // I don't want do (A*)a in my project. qDebug()<<"Problem wrong answer:"; ((Base*)(aa))->createTemp(); qDebug()<<"Soluation:"; ((void(*)())(((Base*)(aa))->mCreateTemp))(); } };

Problem wrong answer:
TempB
Soluation:
TempA

输出:

B

简化问题: 我试图在A* test = new A; ((Base*)test)->createTemp(); 类中执行类似的操作:

TempA

我想创建{ to : deviceid data : { title : "Push Notification", body : "This is a push Message", userId: 10, } }

我已经得到了解决方案,将函数存储为指针,但想知道其他更好的方法。

1 个答案:

答案 0 :(得分:0)

如何使用真正的基类:

class Base : public QObject
{
public:
    virtual void print() const = 0;
};

template<typename T>
class Wrapper : public Base
{
public:
    void print() const override {
        std::cout << typeid(T).name << std::endl;
        // T t;
        // qDebug()<< t.metaObject()->className();
    }
};

class TempA : public QObject{ Q_OBJECT };
class TempB : public QObject{ Q_OBJECT };

class A : public Wrapper<TempA>{ Q_OBJECT };

class B : public Wrapper<TempB>
{
public:
    B(){
        A a;

        QVariant v = QVariant::fromValue(&a); //This v is actually passed from QML

        QObject* aa = v.value<QObject*>();

        auto* base = dynamic_cast<Base*>(aa);
        if (base) {
             base->print();
        }
    }
};