How to apply function to all elements in array (in C++ template class)
I still think you should use std::transform
:
template <class OutputIter, class UnaryFunction>
void apply_pointwise(OutputIter first, OutputIter last, UnaryFunction f)
{
std::transform(first, last, first, f);
}
This function works not only for std::vector
types but indeed any container that has a begin()
and end()
member function, and it even works for C-style arrays with the help of the free functions std::begin
and std::end
. The unary function may be any free function, a functor object, a lambda expression or even member functions of a class.
As for the problem with std::sin
, this free function is templated and so the compiler cannot know which template instantiation you need.
If you have access to C++11, then simply use a lambda expression:
std::vector<float> v;
// ...
apply_pointwise(v.begin(), v.end(), [](const float f)
{
return std::sin(f);
});
This way, the compiler knows that it should substitute T=float
as the template parameter.
If you can use C functions, you can also use the function sinf
, which is not templated and takes a float
as a parameter:
apply_pointwise(v.begin(), v.end(), sinf);