C++ delegate creation

2019-05-29 00:14发布

I was wondering if theres a way to mimic this delegate behaviour (from C#) in C++

new ModifyTargetingStatus("Reversal", "Reverses physical attacks back at the user", -1, new List<CALL_CONDITION>(){CALL_CONDITION.Targetted}, attemptChange: delegate(CharacterMove move, BattleCharacter[] users, ref BattleCharacter[] targets, BattleCharacter holder, BattleField field)
                {
                    if (targets != null && targets.Length == 1 && targets[0] == holder &&
                        (move.MoveClass == MOVE_CLASS.MC_BASIC_ATTACK ||
                        move.MoveClass == MOVE_CLASS.MC_STACKED_ATTACK) &&
                        !move.MoveFlags.Contains(MOVE_FLAG.MF_UNREFLECTABLE))
                    {
                        targets = users;
                        move.Reflected = true;
                        return true;
                    }
                    return false;
                })

I've looked at boost::function and boost::bind and an article about FastDelegates on code project, but they all seem to require you to define the function somewhere else then bind to it. I'd like to be able to provide the function at object creation if possible

Thanks in advance

标签: c++ delegates
2条回答
别忘想泡老子
2楼-- · 2019-05-29 00:42

C++ (and C) use function pointers instead of delegates. Pointers, unlike references, can have a null assigned to them.

查看更多
可以哭但决不认输i
3楼-- · 2019-05-29 00:47

These are called anonymous functions (lambdas), and aren't supported in C++. From the wikipedia article: "Anonymous functions were added to the C++ language as of C++0x."

查看更多
登录 后发表回答