C++ 中的动作类?(相当于 C#)

Vit*_*meo 2 c# c++ lambda delegates action

在我的 C# 游戏引擎中,我曾经通过向管理器对象添加/删除操作来处理有序绘图,管理器对象按优先级对操作进行排序,然后执行它们。

这是一个非常简化的示例:

class DrawManager
{
    public List<Tuple<Action, int>> DrawActions = new List<Tuple<Action, int>>();
    void Draw() { foreach (var tuple in DrawActions) tuple.Item1(); }
}

class Example
{
    DrawManager manager;

    Example()
    {
        manager.DrawActions.Add(new Tuple<Action, int>(DrawBackground, 0));
        manager.DrawActions.Add(new Tuple<Action, int>(DrawForeground, 100));
    }
    ~Example()
    {
        manager.DrawActions.Remove(manager.DrawActions.Find(x => x.Item1 == DrawBackground));
        manager.DrawActions.Remove(manager.DrawActions.Find(x => x.Item1 == DrawForeground));
    }

    void DrawBackground() { /* draw something */ }
    void DrawForeground() { /* draw something */ }
}
Run Code Online (Sandbox Code Playgroud)

通过添加一些辅助方法,代码在我的引擎中变得非常优雅且易于使用。

我最近转向 C++,但找不到任何简单的方法来实现相同的结果。

我尝试使用std::function,但是为了在对象销毁时删除该方法,我不得不将draw方法存储在调用者拥有的指针中,然后将其包装成一个lambda并传入。非常不优雅和耗时.

有没有办法获得类似于 C# 示例中显示的代码?

Big*_*oss 6

您可以使用std::function代替Action:

typedef std::function<void()> Action;
std::vector<std::pair<Action, int> > DrawActions;
void Draw() {
    for_each(DrawActions.begin(), DrawActions.end(), [](std::pair<Action, int>& a) {
       a.first(); 
    });
}
Run Code Online (Sandbox Code Playgroud)