I need a function wrapper for std::bind that will be called before the function it’s wrapper, passing the arguments along to the wrapped functions.
std::function<void (int)> foo = postbind<int>(service, handle);
I’ve so far got down to that
std::function<void (int)> foo = postbind(service, handle);
How can I remove that template parameter? It seems to come down to the type deduction from the object generation function (postbind) not being intelligent enough.
#include <functional>
template<typename T>
void foo(std::function<void (T)> func)
{
}
void handler(int x)
{
}
int main()
{
foo(handler);
return 0;
}
Says error: no matching function for call to ‘foo(void (&)(int))’
Yet, the code sample:
template<typename T>
void foo(T t)
{
}
int main()
{
foo(99);
return 0;
}
This works. Any ideas how to make this work? I need to be able to pass std::bind to it and have the result cast successfully to std::function.
How can I remove the template parameters? Thanks.
Q. What is service and this class meant to do?
A. Encapsulate a function wrapper that boost::asio::io_service->posts out of the current thread.
Full sourcecode:
#include <iostream>
#include <functional>
#include <memory>
class io_service
{
};
typedef std::shared_ptr<io_service> service_ptr;
template <typename Arg1>
class postbind_impl_1
{
public:
typedef std::function<void (Arg1)> function;
postbind_impl_1(service_ptr service, function memfunc)
: service_(service), memfunc_(memfunc)
{
}
void operator()(Arg1 arg1)
{
// do stuff using io_service
memfunc_(arg1);
}
private:
service_ptr service_;
function memfunc_;
};
template <typename Arg1>
postbind_impl_1<Arg1> postbind(service_ptr service,
typename postbind_impl_1<Arg1>::function handle)
{
return postbind_impl_1<Arg1>(service, handle);
}
// ----------------
void handle(int x)
{
std::cout << x << "\n";
}
int main()
{
service_ptr service;
std::function<void (int)> foo = postbind(service, handle);
foo(110);
return 0;
}
To all the naysayers who said this wasn’t possible 🙂