c++ - 如何使用重载函数作为函数模板的参数?

标签 c++ templates overloading

我想每个人都有使用如下代码的经验:

void fun(Type1&);
void fun(Type2&);
vector<Type1> vec;
for_each(vec.begin(), vec.end(), fun);

当然不会编译,因为不清楚要传递哪个函数。你常用的解决问题的方法是什么?

我知道这会起作用:

for_each(vec.begin(), vec.end(), (void(*)(Type1&))fun);

但是有更好的想法吗?

最佳答案

一种解决方案是使用模板函数:

template<typename T>
void fun(T&);
// specialize fun for Type1 and Type2
...
for_each(vec.begin(), vec.end(), fun<Type1>);

更好的方法是将仿函数与模板 operator() 一起使用:

struct fun
{
  template<typename T>
  void operator()(T&) const;
};
...
for_each(vec.begin(), vec.end(), fun()); // T for operator() will be deduced automatically

关于c++ - 如何使用重载函数作为函数模板的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3035292/

相关文章:

c++ - 如何使用模板生成整数序列在这里工作

c# - : this() As a constructor

c++ - 如何在 Qt 中检查我的应用程序的内存使用情况

c++ - 生成文件 | Make 后清理 - 错误 : No such file or directory | Error: recipe for target * failed

c++ - 如何使用 HTML 格式和可点击的单元格制作快速的 QTableView?

c++ - Variadic 模板候选者不匹配

c++:为什么调用 foo(X&) 而不是 foo(X&&)?

c++ - 初始化和访问可变类模板的成员

haskell - 类型类和重载,有什么联系?

c++ - 模板类中重载函数的条件编译