Boost logo

Boost :

Subject: [boost] [boost::bind] How does it works for overloaded member functions in this example?
From: Chaos A.D. (chaos-ad_at_[hidden])
Date: 2010-10-01 05:35:39


   Hi there! Recently I was extremely surprised by the fact that boost::bind
   can handle the case of binding overloaded member functions!

   Here is the simplified testcase, which works fine in gcc 4.4.3.

   #include <boost/bind.hpp>
   struct Test
   {
       static void Func(int) {};
       static void Func(int, const char*) {};
   };

   int main(int argc, char **argv)
   {
           boost::bind(&Test::Func, 5)();
           boost::bind(&Test::Func, 5, "WORKS!")();
           return 0;
   }

   In full testcase i tried to reproduce simplified boost::bind logic, and
   ensured, that my simplified version is still incorrect:
   #include <boost/bind.hpp>

   template <class A1>
   class Args1
   {
       template <class Fn>
       void call(Fn fn)
       {
           fn(a1);
       }

       A1 a1;
   };

   template <class A1, class A2>
   class Args2
   {
       template <class Fn>
       void call(Fn fn)
       {
           fn(a1, a2);
       }

       A1 a1;
       A2 a2;
   };

   template <class Fn, class Args>
   struct bind_t
   {
       bind_t( Fn fn, Args const& args ) : fn_(fn), args_(args) {}

       void operator()()
       {
           args_.call(fn_);
       }

   private :
       Fn fn_;
       Args args_;
   };

   template <class Fn, class A1>
   bind_t< Fn, Args1<A1> > bind(Fn fn, A1 a1)
   {
       typedef Args1<A1> args;
       return bind_t<Fn, args>(args(a1));
   }

   template <class Fn, class A1, class A2>
   bind_t< Fn, Args2<A1, A2> > bind(Fn fn, A1 a1, A2 a2)
   {
       typedef Args2<A1, A2> args;
       return bind_t<Fn, args>(args(a1, a2));
   }

   struct Test
   {
       static void Func(int) {};
       static void Func(int, const char*) {};
   };

   int main(int argc, char **argv)
   {
           boost::bind(&Test::Func, 5)();
           boost::bind(&Test::Func, 5, "WORKS!")();
           bind(&Test::Func, 5)();
           bind(&Test::Func, 5, "NOT WORKS!")();
           return 0;
   }


Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk