【发布时间】:2015-09-18 05:29:18
【问题描述】:
我一直在尝试设置一种方法,可以使用模板检测类的类型,然后返回一个与他的类相关的列表。
这就是我所拥有的。
template <typename T>
list<T>* foundsType(T* t)
{
string array[5] = {"Medic", "Dept", "Patient", "Form", "Bed"};
list<T>* types[] = {medics,depts,pacients,forms,beds};
for (int i = 0; i < 5; i++) {
string obj = typeid(t).name();
if(obj == array[i])
return types[i];
}
}
(medics、depts、patients、forms 和 beds 是使用此方法的类的私有属性)
我知道数组“types”的声明不正确,但我不得不尝试。
【问题讨论】:
-
你能告诉我们你打算如何使用这个功能吗?
-
typeid(t).name()仅适用于调试目的。我们肯定需要更多背景信息。 -
它被用于另一种可以在列表中找到特定对象的方法。像这样:
template <typename T> bool findsObject(T* t){ list<T>* list = foundsType(t); typename list<T>::iterator it; for(it = list->begin(); it != list->end(); it++){ if(*t == *it) return true; } return false; } -
奇怪的是你在 list 上而不是直接在 list 上有指针。