c++集合类调用子函数
C++ collection class to call children functions
我正在做的项目有一些非常讨厌的集合类,我觉得可以重新设计一下。我真的很想做一个集合模板类,它接受模型实例,并提供一种方法来调用集合中每个子元素的特定类型函数。例如:
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
相关文章:
- 禁止子函数调用父级的抽象(或虚拟)函数
- 如何使基类从子类调用覆盖函数
- 添加字符串类型的类成员会导致调用基类函数而不是子函数
- C++调用子函数
- C++,当函子不是一个选项时,我如何编写带有自定义函数调用的模板化 RAII 包装器?
- 如何在C++从父实例调用子函数
- CRTP 在父级析构函数中调用子函数
- 字符串为函数,由其他子类调用,具有整数值
- 子类/超类的"无匹配函数调用"
- 在函数和子函数中调用相同的关键部分
- 整数模板参数和子函数调用
- 子类调用意外的重载函数
- 子类中的方法不会被父类中的虚函数调用
- 如何从同一类的另一个成员函数调用函子
- C ++如何使用子类调用函数,具有超类指针
- 将基类 2 参数构造函数调用到子类 1 参数构造函数中
- 超类和子类,不同的函数调用取决于子类
- 如何防止调用函数调用正在被销毁的子类实例
- 函数调用父类方法而不是子类方法
- 子类中的虚拟函数调用父函数一次