我试图编写一个STL方法来获取向量的日志:
for_each(vec.begin(),vec.end(),log);
Run Code Online (Sandbox Code Playgroud)
但我明白了
no matching function for call to ‘for_each(__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, __gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >, <unresolved overloaded function type>)’
Run Code Online (Sandbox Code Playgroud)
我收集的是由于日志功能的多个版本.显然我可以在日志函数周围编写一个简单的包装器并用它调用它.有没有更简单的方法来指定我想要内联的日志功能?
Yes. You can cast the function to the appropriate type:
for_each(vec.begin(),vec.end(),(double(*)(double))log);
Run Code Online (Sandbox Code Playgroud)
另一种可能性是创建可以接受任何类型的仿函数:
struct log_f
{
template <class T> T operator()(const T& t) const { return log(t); }
};
for_each(vec.begin(),vec.end(), log_f());
Run Code Online (Sandbox Code Playgroud)
而且,正如Billy O'Neal指出的那样,你想要而transform不是for_each.