I am trying to replace all macros in my code with templates. I have a macro that binds this
as the first argument to a function so that a member function can be used in a static context. How can I achieve that with templates?
I would like this functionality:
#define BIND_EVENT_FN(func) std::bind(&func, this, std::placeholders::_1)
Or with lambdas:
#define BIND_EVENT_FN(func) [this](Event& e){ return func(e); }
Something along the lines of this, but obviously not quite like this because this does not compile:
template<class T>
auto bind_event_fn(T& func)
{
return [this](Event&& e){ return func(e); };
}
Minimal working example below, is it possible to replace the macro?
#include <functional>
#include <iostream>
#define LAMBDA_BIND_FN(fn) [this](const int& event) { return fn(event); }
#define BASIC_BIND_FN(func) std::bind(&func, this, std::placeholders::_1)
void run_in_static_context(std::function<void(const int&)> fn)
{
fn(42);
}
class A {
public:
A()
{
run_in_static_context(LAMBDA_BIND_FN(A::member_fn));
}
private:
void member_fn(const int& event)
{
std::cout << "Event: " << event << std::endl;
}
};
int main()
{
A();
}