我希望下面
代码中的
executor
模板是一个独立的C++文件,以减少编译时间并提高绝缘性。
它作为模板工作得很好,但我看不到一种简单的方法来处理具有不同签名的函数而无需模板实现。
是否可以使用
std::mem_fn
、std::function
、std::bind
等?我感觉应该有简单的包装方式,但是没看到。
#include <functional>
#include <iostream>
struct Point {
int x=0, y=0;
};
struct Renderable
{
virtual void OnMouseMove([[maybe_unused]] const Point& pt)
{ std::cout << "OnMouseMove" << std::endl; }
virtual void OnMouseWheel([[maybe_unused]] const Point& pt, [[maybe_unused]] int zDelta, [[maybe_unused]] int fwKeys)
{ std::cout << "OnMouseWheel" << std::endl; }
};
void executor(auto fn, const Point& pt, auto ...args)
{
/* Some internal logic to handle many renderable objects */
Renderable renderable;
fn(renderable, pt, args...);
}
int main()
{
Point pt;
auto fn1 = std::mem_fn(&Renderable::OnMouseMove);
auto fn2 = std::mem_fn(&Renderable::OnMouseWheel);
executor(fn1, pt);
executor(fn2, pt, 0, 0);
}
是的,可以通过让 lambda 表达式和 std::function 为您完成工作,如下所示:
#include <iostream>
#include <functional>
struct Point {
int x=0, y=0;
};
struct Renderable
{
virtual void OnMouseMove([[maybe_unused]] const Point& pt)
{ std::cout << "OnMouseMove" << std::endl; }
virtual void OnMouseWheel([[maybe_unused]] const Point& pt, [[maybe_unused]] int zDelta, [[maybe_unused]] int fwKeys)
{ std::cout << "OnMouseWheel" << std::endl; }
};
struct Executor
{
void execute(std::function<void()> fn)
{
fn();
}
};
int main()
{
Renderable renderable; // is going to be passed by reference to lambdas, MUST outlive executor
Executor executor; // completely independent of renderable now
Point pt;
// if executore makes a threadswitch pt may need to be captured by value!
executor.execute( [&renderable, pt]{ renderable.OnMouseMove(pt); });
executor.execute( [&renderable, pt]{ renderable.OnMouseWheel(pt,0,0); });
}