【问题标题】:How can I create a method that relates a template object with his own template list?如何创建将模板对象与他自己的模板列表相关联的方法?
【发布时间】: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];
    }
}

medicsdeptspatientsformsbeds 是使用此方法的类的私有属性)

我知道数组“types”的声明不正确,但我不得不尝试。

【问题讨论】:

  • 你能告诉我们你打算如何使用这个功能吗?
  • typeid(t).name() 仅适用于调试目的。我们肯定需要更多背景信息。
  • 它被用于另一种可以在列表中找到特定对象的方法。像这样:template &lt;typename T&gt; bool findsObject(T* t){ list&lt;T&gt;* list = foundsType(t); typename list&lt;T&gt;::iterator it; for(it = list-&gt;begin(); it != list-&gt;end(); it++){ if(*t == *it) return true; } return false; }
  • 奇怪的是你在 list 上而不是直接在 list 上有指针。

标签: c++ list templates


【解决方案1】:

你可以使用专业化:

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); }

【讨论】:

  • 这应该放在头文件还是.cpp中?
  • 对于第一个,声明(包括特化)应该放在标题中,定义可以放在 cpp 文件中。第二个是标题。 (除非您只在一个 cpp 中使用该功能,所有可能都放在 cpp 文件中)。
猜你喜欢
  • 2022-10-20
  • 1970-01-01
  • 2012-08-14
  • 2011-02-19
  • 1970-01-01
  • 1970-01-01
  • 2023-04-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多