c++ - 我可以注册一个根据定义其类型的字符串调用特定模板函数的函数吗?

标签 c++ qt templates metadata

我为 Qt 写了一个小编辑器。它接受一个指针,并根据属性的类型(由字符串确定),使用模板函数从中提取数据。

(例如,如果类型是“点”,它将在指针上调用 getBoundValue<QPoint3>。)

这在实践中效果很好。但我将它设置为一个库,以便其他人可以使用它,我假设他们会想要添加对其他类型的支持。问题是我不希望他们必须修改原始源代码,而是从类继承或为新类型注册回调。我不知道如何实现后一个选项,因为我不能同时传递字符串类型和类类型,对吗?

如果我想让用户添加对他们自己的类型的支持,他们是否必须实现我的属性编辑器的子类来处理这些值?或者有没有一种方法可以重新组织我的代码,以便用户可以传递处理新类型(如“矩形”)的功能,以及一个调用 getBoundValue<Rectangle>() 的矩形类型。 ?

这是一些示例代码,我可以在其中查看对象是否属于某种类型。如果是这样,我会在其上调用匹配的模板函数:

AttributeEditor::update(Bindable* instance) {
    _instance = instance;
    clear();

    for (int i = 0; i < _instance->attributeCount(); i++) {
        Attribute attr = _instance->at(i);

        QList<QStandardItem*> attributeRow;
        QStandardItem* nameItem = new QStandardItem(
            attribute->property("name").toString()
        );

        attributeRow << nameItem;

        QList< QList<QStandardItem*> > subRows;

        if (attr->property("getter").isValid()) {

            std::cout << attr->type().toStdString() << std::endl;

            QString value = "?";
            if (attr->type() == "point3" || attr->type() == "vector3") {
                QVector3D p = getBoundValue<QVector3D>(_instance, attr);

                /* ... */
            }

    /* ... */
}

最佳答案

由于您的代码不知道外部类、模板或其他,您将需要公开接受以下内容的注册机制:

  1. 类型名称(字符串)。例如“矩形”
  2. 接口(interface)

该接口(interface)应该有一个名为getBoundValue 的纯虚方法。所有需要该功能的类都应实现该接口(interface)。

例子:

struct IShape {
   virtual QVector3D getBoundValue() = 0;
   // more shape methods
   ...
};

class Rectangle {
   QVector3D getBoundValue();
};

// register interface prototype - exported from your library
void RegisterShape( IShape* pShape, const QString& name );

关于c++ - 我可以注册一个根据定义其类型的字符串调用特定模板函数的函数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20465066/

相关文章:

c# - VB6/C++ WINAPI 到 C#

qt - 如何使用QTcpSocket进行小数据包的高频发送?

c++ - 在模板化成员函数的返回类型中使用 std::enable_if 时的编译器差异

c++ - 防止静态库中的模板实例化

linux - QProcess 传递(shell)参数

C# 在泛型列表中使用 Equals 方法失败

c++ - 嵌入式设备上使用new或malloc导致的Segment Fault

c++ - std::thread 通过引用传递 vector 元素

c++ - 文档示例中的 Cython 崩溃

c++ - qmake 不添加小部件