bind2nd doesnt accept methods using pass-by-ref?

llewelly@dbritsch.dsl.xmission.com llewelly@dbritsch.dsl.xmission.com
Tue Jun 20 15:47:00 GMT 2000


On Tue, 20 Jun 2000, Rob Willis wrote:

> 
> Still learning the ins and outs of STL.  I hit the following case, where
> bind2nd can not take accept methods that use pass-by-reference.  That
> seems very limiting...  I looked in the bind2nd definition, it appears
> as if the bind2nd template is saving a copy of the value to be passed
> into the method - is this what the standard requires??  

Yes... see 20.3.6 . Note bind1st() works the same way.

> Seems like in
> many cases you would want the bind2nd to just save a ref to the value...

Maybe ... but I have had occasion to store the function object returned
  from bind2nd() so that it outlives the original variable from which it
  got its parameter value. 

But that doesn't matter; the standard says it keeps a full copy.

> 
> -Rob
> 
> rob@e-critical.com
> 
> 
> #include <functional>
> #include <algorithm>
> #include <vector>
> 
> using namespace std;
> 
> class Base
> {
> public:
> 
> virtual void testOp1( const double * d_ptr ) = 0;
> 
> virtual void testOp2( const double & d_ref ) = 0;
> };

I supose you could try a quick hack like this:

template <class _Ret, class _Tp, class _Arg>
class mem_fun_remove_ref_to_const1_t  
  :public std::binary_function<_Tp*,_Arg,_Ret>
{
public:
  explicit mem_fun_remove_ref_to_const1_t(_Ret (_Tp::*__pf)(_Arg
const&)) : _M_f(__pf) {}
  _Ret operator()(_Tp* __p, _Arg __x) const { return (__p->*_M_f)(__x); }
private:
  _Ret (_Tp::*_M_f)(_Arg const&);
};

template <class _Ret, class _Tp, class _Arg>
inline mem_fun_remove_ref_to_const1_t<_Ret,_Tp,_Arg>
mem_fun_remove_ref_to_const(_Ret (_Tp::*__f)(_Arg const&))
  { return mem_fun_remove_ref_to_const1_t<_Ret,_Tp,_Arg>(__f); }


> 
> int main()
> {
> std::vector< Base * > vObjects;
> double  d_value = 1.0;
> 
> // this compiles
> for_each( vObjects.begin(), vObjects.end(),
> bind2nd( mem_fun( &Base::testOp1 ), &d_value ) );
> 
> /* // this doesnt compile
> for_each( vObjects.begin(), vObjects.end(),
> bind2nd( mem_fun( &Base::testOp2 ), d_value ) );
> */
> }
> 
> 
> 





More information about the Libstdc++ mailing list