i have a question about for_each
-
why can i code like this:
#include #include #include #include using namespace std;
template void OUT(T c)
{
cout << "!!" << c ;
}int main()
{
vector st(10, " ");for\_each(st.begin(), st.end(), OUT);
}
i know information about for_each : /*template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function f); Apply function to range Applies function f to each of the elements in the range [first,last).*/ but why they don't use Function Templates instead of function, thank you
-
why can i code like this:
#include #include #include #include using namespace std;
template void OUT(T c)
{
cout << "!!" << c ;
}int main()
{
vector st(10, " ");for\_each(st.begin(), st.end(), OUT);
}
i know information about for_each : /*template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function f); Apply function to range Applies function f to each of the elements in the range [first,last).*/ but why they don't use Function Templates instead of function, thank you
Not sure to answer your question as it is formatted but
f
can either be a pointer to a function or an object whose class overloadsoperator()(InputIterator::value_type)
. See http://www.cplusplus.com/reference/algorithm/for_each/[^] cheers, ARWhen the wise (person) points at the moon the fool looks at the finger (Chinese proverb)
-
why can i code like this:
#include #include #include #include using namespace std;
template void OUT(T c)
{
cout << "!!" << c ;
}int main()
{
vector st(10, " ");for\_each(st.begin(), st.end(), OUT);
}
i know information about for_each : /*template <class InputIterator, class Function> Function for_each (InputIterator first, InputIterator last, Function f); Apply function to range Applies function f to each of the elements in the range [first,last).*/ but why they don't use Function Templates instead of function, thank you
This is called 'generic' programming. The term 'generic' means that the definition of the
for_each
function does not assume anything else from the template argument than that it has anoperator()( T )
. If they would have implemented it using a function pointer, # they would have needed to specify the function pointer's type (e.g. void (*) (int)) and thus would have disallowed any other type of function (remember C) # they would have disallowed the use of stateful functions (e.g. accumulators), like often needed for thealgorithms
Also, the usage of templates greatly improves the optimizer's chances: it knows _at compile time_ what the body of thefor_each
block is going to be, so it can often skip parameter pushing etc..., hence reducing function call overhead.