In article <b63330f7-e3e1-4fcc-b25d-ee035894e833
@h11g2000prf.googlegroups.com>,
szhorvat@gmail.com says...
Quote:
>
I am looking for a way to generalize the function template below, so
that it will work with any type, not just double. Is this at all
possible in C++? I'd like to replace double (*fun)(double) with a
generalized A (*fun)(B).
>
>
template<double (*fun)(double)>
array<doubleapply(const array<double&source) {
array<doubleresult(source.size());
for (int i = 0; i < source.size(); i++)
result[i] = fun(source[i]);
return result;
}
As long as you only want to support pointers to functions (not functors)
it's pretty simple -- just templatize the input and output types:
// warning: only minimally tested
//
// This depends on 'array; defining size_type, though size_t would also
// work better than int without that requirement.
//
template <class A, class B>
array<Aapply(const array<B&source, A (*fun)(B)) {
array<Aresult(source.size());
for (typename array<A>::size_type i=0; i<source.size(); ++i)
result[i] = fun(source[i]);
return result;
}
One way to make it work with function objects looks like this:
template <class F>
array<typename F::result_type>
apply(const array<typename F::argument_type&source, F f)
{
typedef typename array<typename F::argument_type>::size_type s_type;
array<typename F::result_typeresults(source.size());
for (s_type i=0; i<source.size(); ++i)
results[i] = f(source[i]);
return results;
}
Since this uses result_type and argument_type, you have to define those,
which is usually done with std::unary_function, something like this:
struct func : public std::unary_function<int, double{
double operator()(int input) { return sqrt(double(input)); }
};
FWIW, you can include both of these to overload apply to work with both
functions and unary_function objects.
--
Later,
Jerry.
The universe is a figment of its own imagination.