|
Boost : |
From: Peter Dimov (pdimov_at_[hidden])
Date: 2002-02-26 07:06:15
From: "rwgk" <rwgk_at_[hidden]>
> The attached code is a simplified fragment from a package
> for numerics with arrays.
>
> There is a scalar function foo() (think foo() is a function
> declared in <cmath>) and an associated function
> array_foo(). Using boost::bind() a pointer to foo() is
> passed to a generic array_unary_function() which loops over
> the array and applies the passed function to each element.
>
> This works if there is just one foo() but fails if there
> are several overloads for foo() (remove the // in line 4
> of the code to see the error).
The example is a bit oversimplified since in
> template <typename ElementType>
> void array_foo(std::vector<ElementType>& a)
> {
> array_unary_function(
> boost::bind(foo, _1),
> &*(a.begin()),
> a.size());
> }
there is no need to use bind at all. 'foo' by itself will work.
> Is it possible to select the correct function in this
> context, i.e. without knowing the exact argument or
> return type? E.g.
>
> boost::bind(select_given_arg_type<ElementType>(foo), _1)
Unfortunately no, it isn't possible to select an overload without specifying
its exact signature. You simply can't pass 'foo' as argument when its
overloaded.
If you need to use <cmath> functions directly, I don't see a solution.
If you are allowed to wrap the functions, the solution is to use a
polymorphic function object:
struct foo
{
int operator()(int x) const { return 2 * x; }
double operator()(double x) const { return 3.0 * x; }
};
_but_ this 'foo' won't work with the short form of boost::bind because its
return type cannot be deduced automatically (no typeof!).
Your original example will work fine because it doesn't need bind; if you
need to bind() foo, you'll have to specify a return type
(boost::bind<ElementType>(foo(), _1) in the example.)
Let me know if this helps.
Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk