【发布时间】:2019-10-16 19:36:25
【问题描述】:
我正在尝试用模板替换我的代码中的所有宏。我有一个将this 作为第一个参数绑定到函数的宏,以便可以在静态上下文中使用成员函数。如何使用模板实现这一点?
我想要这个功能:
#define BIND_EVENT_FN(func) std::bind(&func, this, std::placeholders::_1)
或者使用 lambda:
#define BIND_EVENT_FN(func) [this](Event& e){ return func(e); }
类似这样的东西,但显然不太像这样,因为它不能编译:
template<class T>
auto bind_event_fn(T& func)
{
return [this](Event&& e){ return func(e); };
}
下面的最小工作示例,是否可以替换宏?
#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();
}
【问题讨论】:
-
参数
t在最后一个sn-p中应该是func? -
您需要将
this传递给bind_event_fn以便 lambda 可以捕获它。与宏不同,函数在自己的范围内运行。 -
@foreknownas_463035818 是的,已修复