我有以下問題爭取一些時間:C++方法返回基於一個字符串不同類型
我在我的應用程序的多個數據類型,以及它們的使用類似(非常簡單的代碼):
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;
並且兩個衍生和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:返回基於的方式,我可以自動使用它,而無需指定類型的字符串屬性不同對象的矢量...
C++是一種*靜態*類型的語言。這意味着所有表達式和變量的類型必須是靜態的,即通過檢查程序文本而不必運行它。因此,你想要的是不可能的,你必須重新考慮你的設計。 –