c++集合类调用子函数

C++ collection class to call children functions

本文关键字:子函数 调用 集合类 c++      更新时间:2023-10-16

我正在做的项目有一些非常讨厌的集合类,我觉得可以重新设计一下。我真的很想做一个集合模板类,它接受模型实例,并提供一种方法来调用集合中每个子元素的特定类型函数。例如:

MyCollection<Student> BiologyStudents();
// [Fill the collection]
BiologyStudents.EnrollInClass(ClassList::Biology);
BiologyStudents.Commit();

这个想法是,我可以很容易地使用我的集合在一个班级中注册所有学生,然后将这些更改提交到数据库。我的问题是如何暴露属于孩子学生对象的EnrollInClass()函数?如果我的集合包含与Student不同类型的对象,我希望从集合中公开这些函数。我能想到的唯一方法是用我半有限的c++知识做一个函数,这个函数的参数引用了一个函数,我知道它在包含子类中。如果调用错误的函数或提供错误的参数,这样就不会提供编译错误,所以我希望有一种方法利用编译器来提供这些检查。

这可能吗?如果有,怎么做?作为一个警告,我习惯用Java/c#进行泛型编程,所以我对c++模板的印象可能有点偏离。

一种方法是使用方法指针:

template <typename T>
struct MyCollection {
  template <typename U>
  void ForEach(void (T::*func)(U),U param)
  {
    // for each item loop goes here
    (item.*func)(param);
  }
};

MyCollection<Student> BiologyStudents;
// [Fill the collection]
BiologyStudents.ForEach(&Student::EnrollInClass,ClassList::Biology);

你必须为不同数量的参数提供不同的版本。

在c++ 11中,你可以这样做:
template <typename T>
struct MyCollection {
  void ForEach(std::function<void (T &)> func)
  {
    // for each item loop goes here
    func(item);
  }
};

MyCollection<Student> BiologyStudents;
// [Fill the collection]
BiologyStudents.ForEach([](Student &s){s.EnrollInClass(ClassList::Biology);});

不需要为不同数量的参数创建不同版本的ForEach