In C++0X, I want to write generic caller/callback functions using variadic templates. First hurdle: The callees are member functions. So far so good. Second hurdle: There are many overloaded member functions of the same name.
How would I solve this? My primary reference is this fine article, but I can't quite make it work.
OK, let's dive in:
Class Foo
{
void bar(int ID, int, int) { ... }
void bar(int ID) { ... }
void bar(int ID, double, float, void(Baz::*)()) const { /* jikes */ }
template<typename ... Args>
void sendBarToID_15(std::function<void(int, Args...)> refB, Args ... args)
{
refB(15, args...);
}
void yum()
{
sendBarToID_15(&Foo::bar, this, 17, 29); // want first version
}
};
However, I cannot compile the call in yum() because the overload prevents template resolution. According to the referenced article, I should explicitly create a function object
f = magic::make_function<help, me>(&Foo::bar)
and then leisurely call sendBarToID_15(f, this, 17, 29)
.
How can I make this work?
Bonus points for std::bind magic that obviates "this" in the last line.
Extra bonus points for making 15 parametric in a useful way.
Lots of thanks!!
Use a lambda function- this kind of thing isn't necessary anymore.
Is this what you're looking for?
To follow up Howard's fine answer, let me just state that in the end I conclude that making the sendBarToID function templated doesn't really improve the logic of the setup in the way I had hoped. Since we have to bind() anyway, there's no reason to first bind and then unbind placeholders, we might as well just bind everything right in place. Here's the non-templated version:
I was hoping that the variadic template solution could somehow make the client code simpler, but now I don't see how it can get any simpler than this. Variadic #define macros take care of the rest.
Thank you for the contributions!
Update: OK, here's what I finally came up with, thanks to preprocessor macros:
There is one inconvenience: I need to define two separate functions and macros for constant and non-constant member functions. Also, I can't handle the empty argument list (Foo::bar(int)).
You are trying to call bar with the following arguments in order : 15, this, 17, 29.
You want : this, 15, 17, 29
So &Foo::bar can't be a std::function
If you can use lambda I'd use :
if you can't implement it with an helper class:
or using bind: