Skip to main content

C++ tricks, #4: Binding to overloaded member functions

Anyone who is developing with C++ knows the joys of member functions and pointers to member functions (you know, those SomeLongType (ClassName::*)(Param)-typed beasts). Today, I had a problem, I needed to bind (using Boost.Bind) to an overloaded member function, and to make things interesting it was const as well. The problem is with just a plain &Class::functionName (i.e., boost::bind (&Class::fun, &instance, _1, ...)), it cannot resolve which function you mean (giving you usually pages of compiler output). The deal is, how to disambiguate, and the solution is of course cast to your type. This leads to something like

boost::bind (static_cast<int (ClassName::*)(const Param& p1) const> (&ClassName::Function), &instance, _1)

Hope this helps somebody as it took me quite some time to figure this out.