In article <>, Jon Rea <> wrote:
> Daniel T. wrote:
> > In article <>, Jon Rea <>
> > wrote:
> >
> >> Hello all,
> >>
> >> Sorry if this is long, but I wanted to be specific...
> >>
> >> Can anyone shed any light on the following errors in the context of the
> >> following example code:
> >>
> >> cullMethod1(); // compiles, but not what we want - we cant access
> >> m_Exclustions
> >>
> >> cullMethod2(); // fine but long-winded and causes many array re-allocations
> >>
> >> cullMethod3(); // doen't compile!
> >>
> >> i.e. How do you pass a member function to std functions.
> >
> > First change the signature for Matches:
> >
> > bool Matches(Bond bond) const
> > {
> > ...
> > }
> >
> > Then you can:
> >
> > void cullMethod1()
> > {
> > m_Bonds.erase(remove_if(m_Bonds.begin(), m_Bonds.end(),
> > bind1st(mem_fun(&MyDerived::Matches), this)), m_Bonds.end());
> > }
> >
>
> Thanks for the reply. Thats better!
>
> What though if I had to use:
> bool Matches(BIG_Bond& bond) const;
> because copying a 'BIG_Bond' is an expensive operation.
Test first. I would not be surprised to find that the compiler optimized
the copy away if the Matches function doesn't modify the parameter in
any way.
However, if you absolutely *had* to use a const& the you can always
create your own selector and then use:
m_Bonds.erase(remove_if(m_Bonds.begin(), m_Bonds.end(),
selector(&MyDerived::Matches, this)), m_Bonds.end());
Before I show you what "selector" looks like, you may be interested in
how I developed it. I put the above code in as the interface I wished,
and then fixed the compile errors until I had something that ran. After
than, I substituted templated tyeps. QED
template < typename Ret, typename Tp, typename Arg >
struct selector_t : unary_function< Arg, Ret >
{
Ret (Tp::*mfn)(Arg) const;
const Tp* obj;
selector_t(Ret(Tp::*x)(Arg) const, const Tp* y): mfn(x), obj(y) { }
Ret operator()(Arg x) const {
return (obj->*mfn)(x);
}
};
template < typename Ret, typename Tp, typename Arg >
selector_t< Ret, Tp, Arg > selector(Ret(Tp::*x)(Arg) const, Tp* y) {
return selector_t< Ret, Tp, Arg >(x, y);
}
And yes, I double checked. Arg in the above template is a "const Bond&"
and not a "Bond".
--
To send me email, put "sheltie" in the subject.
|