c++ - 我如何创建一个将模板对象与其自己的模板列表相关联的方法?

标签 c++ list templates

我一直在尝试设置一种方法,该方法可以使用模板检测一种类型的类,然后返回与其类相关的列表。

这就是我的。

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/

相关文章:

c++ - ADL 在 constexpr 函数中不起作用(仅限 clang)

C++ - ifstream 不喜欢相对路径

python - 如何按字典的值对字典列表进行排序?

Python:为什么交换最大和最小数字的代码不起作用?

list - Haskell - 如何以优雅的方式以相反的顺序迭代列表元素?

c++ - 双模板函数重载失败

c++ - 检查特定目录中是否存在与 abc* 匹配的文件的最佳方法

c++ - 默认构造函数 C++ 错误

c++ - 将元组参数转发给 VS2012 中的函数

c++ - 如何将 C++ 宏转换为更优雅的解决方案