1

How do I achieve the following overloaded method call

class Foo {
    void bind(const int,boost::function<int (void)> f);
    void bind(const int,boost::function<std::string (void)> f);
    void bind(const int,boost::function<double (void)> f);
};

First attempt

SomeClass c;
Foo f;
f.bind(1,boost::bind(&SomeClass::getint,ref(c));
f.bind(1,boost::bind(&SomeClass::getstring,ref(c)));
f.bind(1,boost::bind(&SomeClass::getdouble,ref(c)));

Then I found a possible answer so tried this:-

f.bind(static_cast<void (Foo::*)(int,boost::function<int(void)>)>(1,boost::bind(&SomeClass::getint)));

which looks ugly but might work?

but gives and error

error C2440: 'static_cast' : cannot convert from 'boost::_bi::bind_t<R,F,L>' to 'void (__cdecl Foo::* )(int,boost::function<Signature>)'

Any ideas I can make this overloading work. I suspect type erasure is occuring but the compiler obviously recognises the overloaded methods since Foo.cpp compiles fine

Community
  • 1
  • 1
Delta_Fore
  • 3,079
  • 4
  • 26
  • 46

1 Answers1

2

The possible answer you link to is solving a different problem: choosing between function overloads when taking a pointer to that function. The solution is to explicitly cast to the correct function type, since only the correct function is convertible to that type.

Your problem is different: choosing between overloads when calling the function, when there's no clear conversion to any of the overloaded parameter types. You can either convert explicitly to the function type:

f.bind(1,boost::function<int (void)>(boost::bind(&SomeClass::getint,boost::ref(c))));

or, in C++11, use a lambda:

f.bind(1,[&]{return c.getint();});

(and you'd probably prefer std::function to boost::function in C++11).

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644
  • Works perfectly, and yes I switched to std::function. I'm guessing there is no way of having the compiler deduce the casting arguments through the use of a factory function? – Delta_Fore Aug 01 '13 at 16:16