C++ 方法基于字符串返回不同的类型
c++ method returning a different type based on a string
我正在与以下问题斗争一段时间:
我的应用程序中有几种数据类型,它们的使用方式如下(非常简化的代码(:
QVector<Function*> Container::getFunctions() {return mFunctions};
QVector<Procedure*> Container::getProcedures() {return mProcedures};
....
QVector<Function*> mFunctions;
QVector<Procedure*> mProcedures;
Function
和Procedure
都派生自ObjectWithUid
具有
virtual QString getClassUid() = 0;
并且Function
和Procedure
都在实现虚拟方法,并且每个都返回各自的类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>
。
相关文章:
- 如何在模板参数中分离函数类型返回类型和参数
- 为什么要为指针返回类型返回一系列字符?
- 有没有办法根据运行时值的类型返回 constexpr 对象
- 从弱指针返回类型返回共享指针
- 无法为unique_ptr返回类型返回 nullptr
- 为什么双重类型返回无穷大
- std::is_arithmetic 为通用 lambda 中的 int 类型返回 false:未定义的行为?
- C 策略设计具有可变类型返回值
- 根据类型返回一个值
- 在C++中,将double转换为long的类型返回了不正确的值
- 作为宏参数的安装类型返回错误:字符串常量之前的预期非限定 id
- 具有引用类型返回的函数
- C++ 如何使模板<T>f() 为整数 T 返回 -1,为指针类型返回 nullptr
- C++模板:按类型返回值
- 以Integer返回类型返回浮点值
- 使用 C++14 的自动功能类型返回扣除代替 std::common_type 是否始终安全?
- 为什么允许新运算符向每个指针类型返回*void
- 适当的函数返回类型返回日期时间
- c++中布尔类型返回函数的默认返回值
- 在c#中使用非托管c++代码对所有double类型返回0