The third argument of for_each() is not just a function name (string). It has type UnaryFunction!
So, you are in fact passing a function object (effectively a pointer to your timesTwo() function) into the for_each() function.
1 2
template<class InputIt, class UnaryFunction>
UnaryFunction for_each(InputIt first, InputIt last, UnaryFunction f);
[...] f - function object, to be applied to the result of dereferencing every iterator in the range [first, last)
The signature of the function should be equivalent to the following: void fun(const Type &a);
No. You are effectively passing a pointer to your TimesTwo() function into the for_each() function.
The for_each() function then invokes the given function f – it doesn't really care which function has been passed, as long as that function has the "proper" signature – on every element in the given range.
So, for_each() invokes the function f, via the given function pointer. And, whenever it does so, it passes the required argument to f.
(That's similar to how foo() passes the argument to the given func in my previous example)
@kigar64551
so the for_each() will invoke the function timesTwo and as long as the vector type matches the function parameter type and the number of parameter in timesTwo is correct (in this case, only one parameter)
and each time the for_each() will pass the argument to the function timesTwo?
But, note that for_each() is a template function. So the argument type is not fixed! The only requirement is that the given UnaryFunction accepts a single argument of the same type that we get by dereferencing the given InputIt.
In your case, values.cbegin() returns an iterator that dereferences to int values. That is because values is of type array<int, SIZE>. Consequently, the UnaryFunction passed to for_each() must accept a single argument of type int to match the given input iterator.
If the input iterator had a different type, then you'd have to adjust the argument type of your UnaryFunction accordingly.
The template arguments _InputIterator and _Function are replaced with the concrete types to create a concrete instantiation of the template function. In your example, the concrete instantiation of for_each() would look something like this: