我想每个人都有使用如下代码的经验:
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/