如何设置模板参数以允许灵活选择不同类型的函数
How to set the template parameter to allow flexibility in choosing different kinds of functions
例如
template<class D, Function>
struct A
{
void foo()
{
D d;
int i = Function(d);
// Here function can be a free function: int fun(D& d)
// or member function: int D::fun()
// or function object:
}
};
如何设置模板参数以允许在选择不同类型的函数时具有灵活性?代码可以更改,只允许灵活性很好。感谢
最好将函数传递到类中。如果你不传递一些对象,你就必须去构造这样一个对象来调用:
template<class D, typename Function>
struct A
{
explicit A(Function f) : func_(f) { }
void foo()
{
D d;
int i = func_(d);
// Here function can be a free function: int fun(D& d)
// or member function: int D::fun()
// or function object:
}
Function func_;
};
由于可调用类型几乎总是无状态的或具有微小的内部状态,因此复制这些类型不应该有任何影响。
相关文章:
- 如何使用默认参数等选择模板专业化
- 如何(从固定列表中)选择一个数字序列,该序列将与目标数字相加
- 选择要调用的构造函数
- C++选择排序算法中的逻辑错误
- QTreeView幻灯片多选后无法使用单击选择
- 无法获取菜单选择以运行函数.C++
- Qt C++静态thread_local QNetworkAccessManager是线程应用程序的好选择吗
- 在C++中,如何通过几种类型从元组中选择多个元素
- 讨论 - 创建矩阵时的数组与向量的向量 - 什么是最实用的选择
- 对可变参数使用声明.如何选择正确的功能
- 选择选举获胜者的程序
- 如何选择在 csv 文件中输出的位置
- 根据用户回答声明"Players"。用户选择玩家数量。播放器是结构体
- 程序在尝试猜测它选择的随机数时进入无限循环?
- 选择和修改嵌套向量中的条目的最佳实践
- 在PostgreSQL中根据它们的ID选择大量行的最快方法是什么?
- 表达式 SFINAE:如何根据类型是否包含具有一个或多个参数的函数来选择模板版本
- 在运行时选择父类的实现
- 数数并选择 sqlite 中的前三名
- 如何设置模板参数以允许灵活选择不同类型的函数