Re: std::transform ugly cast
Dilip wrote:
I was reading the C++ templates (Josuttis et al) book and came across
an example that left me scratching my head.. there is a function
template:
template<typename T, int val>
T addvalue(T const& x)
{
return x + val;
}
that is used in transform like so:
std::transform(source.begin(), source.end(), dest.begin(),
addvalue<int, 5>);
the author goes on to say that because of some function template
overload issues we actually need to cast the last parameter like this:
(int(*)(int const&)) addvalue<int, 5>
can someone please enlighten me? why is the cast needed?
I don't think it is needed. Have you tried without it? Do you get any
compiler error message?
#include <algorithm>
#include <vector>
template<typename T, int val>
T addvalue(T const& x)
{
return x + val;
}
int main() {
std::vector<int> source, dest;
// that is used in transform like so:
std::transform(source.begin(), source.end(),
dest.begin(), addvalue<int, 5>);
}
i also
don't understand (embarassingly) what it means to say int(*)
int(*)(...)
Is a nameless declaration meaning "a pointer to a function that takes
.... arguments and returns an int.
Just for using a C-style cast and insisting on its necessity the
author should join Schildt in exile!
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask