我正在尝试用模板替换代码中的所有宏。我有一个宏,它将 this
绑定(bind)为函数的第一个参数,以便可以在静态上下文中使用成员函数。如何使用模板实现这一目标?
我想要这个功能:
#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();
}
最佳答案
I am trying to replace all macros in my code with templates.
你不能。虽然模板可以做很多事情,但有很多事情只能通过宏来处理。
模板是生成类型、函数或变量的模式。因此,它们必须遵守 C++ 类型、函数或变量的规则。 (非 lambda)函数定义无法进入其声明的范围并只能将内容取出。例如this
。函数的作用域是隔离的;它无法访问其范围之外的事物(全局变量和类成员之外)。
因此,模板函数也无法做到这一点。两阶段查找确实允许模板在某种程度上受到基于实例化位置的可访问名称的影响,但这非常有限,在这种情况下根本没有帮助。
您无法从实例化模板的位置自动进行模板实例化导入this
。您可以将 this
作为参数传递给函数,并且它可以在绑定(bind)表达式中使用该值,但模板无法自行找到 this
.
关于c++ - 如何使用模板而不是宏来绑定(bind) 'this'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58420559/