C++ 方法基于字符串返回不同的类型

c++ method returning a different type based on a string

本文关键字:类型 返回 字符串 方法 C++      更新时间:2023-10-16

我正在与以下问题斗争一段时间:

我的应用程序中有几种数据类型,它们的使用方式如下(非常简化的代码(:

QVector<Function*> Container::getFunctions() {return mFunctions};
QVector<Procedure*> Container::getProcedures() {return mProcedures};
....
QVector<Function*> mFunctions;
QVector<Procedure*> mProcedures;

FunctionProcedure都派生自ObjectWithUid具有

virtual QString getClassUid() = 0;

并且FunctionProcedure都在实现虚拟方法,并且每个都返回各自的类UID(对于函数,这是"CUID_FUNC",对于过程,这是"CUID_PROC"(。

现在,我在其他地方有一个方法:

template <class T> void showObjectList(const QVector<T*> items)
{
   // show the list of objects
}

其用法如下:

showObjectList(getFunctions());

showObjectList(getFunctions());

正如预期的那样,我可以显示函数或过程。

但是现在我希望能够根据某个对象的类 uid 显示列表,所以我需要这样的代码:

ObjectWithUid* obj = giveMeMyObject();
showObjectList(< a vector to which the object belongs determined based on class UID >)

问题从这里开始

我写了以下方法:

template <class T> QVector<T*> getListOfObjectsForUid(const QString& uid)
{
    if(uid == uidFunction)
    {
        return getFunctions();
    }
    return QVector<T*>();
}

我正在尝试像这样使用它:

ObjectWithUid* obj = giveMeMyObject();
showObjectList(getListOfObjectsForUid(obj->getClassUid()));

编译器大喊:error: no matching function for call to getListOfObjectsForUid(const QString&) candidate is template <class T> QVector<T*> getListOfObjectsForUid(const QString& uid)

怎样才能实现我想要的?IE:基于字符串属性返回不同对象的向量,我可以自动使用它而无需指定类型...

您必须以某种方式指定静态 T。

  showObjectList(getFunctions());

隐式指定T=Function*,但是

  showObjectList(getListOfObjectsForUid(obj->getClassUid()));

不明确getListOfObjectsForUid因为返回类型中只有模板参数。

您可以手动解决歧义:

  showObjectList(getListOfObjectsForUid<ObjectWithUid>(obj->getClassUid()));

由于所有对象类型都继承自ObjectWithUid,并且返回类型实际上是QVector<ObjectWithUid*>的,而不仅仅是QVector<ObjectWithUid>