C++ delegate creation

2019-05-29 00:23发布

问题:

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

回答1:

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."



回答2:

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



标签: c++ delegates