c++ - 将类名插入容器

标签 c++ qt templates

我有几个派生自 QWidget 的类 我也有这样的模板函数

    template<typename T>
    QWidget* create(){return static_cast<QWidget*>(new T());}

现在我要创建容器:

    QMap<int, className> classes // it is not compiling 

因此,我可以将容器值用作函数模板类型:

    QWidget* widget = create<classes[i]>();

我应该怎么做?

最佳答案

类不是 C++ 中的一流对象(即它们不是可以传递或存储在容器中的数据)。有一些东西与类“名称”相似,但实际上您不能保证它是一个可读的名称,并且无论如何您都不能创建给定该名称的实例。

你可以做的是制作一个从 intfunction pointers 的映射,因为它们是一流的对象:

#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "derivedwidget.h"
#include <QMap>

template<typename T>
QWidget *create() { return new T; }

QMap<int, QWidget *(*)()> wmap;

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

    wmap[1] = &::create<DerivedWidget>;

    this->setCentralWidget(wmap[1]());
}

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

关于c++ - 将类名插入容器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28505455/

相关文章:

C++ 通用表数据结构

c++ - 如何设计一个Qt前后端分离的程序?

java - 在 jar 文件中加载速度模板

C++ 返回多种类型作为引用

python - mac osx 上的 pyside 导入错误

c++ - 类模板的静态成员是否被隐式实例化?

c++ - QMenu 无模式/异步

c++ - 如何验证传递给模拟函数的参数的派生类型

c++ - 优化 I/O 绑定(bind)的 Win32 应用程序

qt - 带有qt复选框的文件系统 TreeView