Is this code correct?
It appears to work in g++ 4.8.3 and clang (bcc64), however appearing to work is no guarantee of correctness :)
The aim is to be able to replace a call to a member function:
void Master::go()
{
std::string s;
func(s); // func is a member function of Master
}
with a function template that wraps this call (and would indeed work with any class, not just Master):
void Master::go()
{
std::string s;
call_function( func, s ); // pseudocode
}
which ends up calling this->func(s)
.
The code which seems to work:
#include <iostream>
#include <string>
#include <functional>
struct Master
{
void func(std::string &s) { std::cout << "Master::func(" << s << ")\n"; }
void go();
Master() {}
private:
Master(Master const &);
};
int main()
{
Master m;
m.go();
}
template<typename FuncT>
void call_function( std::function<FuncT> fp, std::string s )
{
fp(s);
}
template<typename FuncT, typename Host>
typename std::function<FuncT> my_binder(Host *h, FuncT Host::*p)
{
using std::placeholders::_1;
return std::bind(p, h, _1);
}
void Master::go()
{
std::string s("hello");
call_function( my_binder(this, &Master::func), s );
}
If the code is correct, then is my function my_binder
a good idea, or am I overlooking a simpler option?