我一直在尝试设置一种方法,该方法可以使用模板检测一种类型的类,然后返回与其类相关的列表。
这就是我的。
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
and beds
是私有(private)的此方法正在使用的类的属性)
我知道数组“types”的声明不正确,但我不得不尝试。
最佳答案
你可以使用特化:
template <typename T> list<T>* foundsType();
template <> list<Medic>* foundsType<Medic>() { return medics; }
template <> list<Dept>* foundsType<Dept>() { return depts; }
template <> list<Patient>* foundsType<Patient>() { return patients; }
template <> list<Form>* foundsType<Form>() { return forms; }
template <> list<Bed>* foundsType<Bed>() { return beds; }
或者您可以用 std::tuple
替换您的变量(自 C++11 起,C++14 为 get
类型,即使它可以写成在 C++11 中):
std::tuple<std::list<Medic>*,
std::list<Dept>*,
std::list<Patient>*,
std::list<Form>*,
std::list<Bed>*> lists;
template <typename T> list<T>* foundsType() { return std::get<std::list<T>*>(lists); }
关于c++ - 我如何创建一个将模板对象与其自己的模板列表相关联的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32644471/