0

它是事件管理器,其工作原理见main()。所以,代码:

class CEventManager
{
public:
    static CEventManager *const GetInstance()
    {
        static CEventManager pInstance;
        return &pInstance;
    };

    template <typename... ARGS>
    bool RegCallback(E_EVSYS_MSG const &_eType, void (*_Func)(ARGS...))
    {
        m_Callbacks[_eType].push_back(_Func);

        return true;
    };

    template <typename... ARGS>
    bool CallEvent(E_EVSYS_MSG const &_eType, ARGS... _Args)
    {
        auto const &FuncsVector = m_Callbacks[_eType];

        for (auto const _Func : FuncsVector)
        {
            typedef void(*FUNC)(ARGS...);
            FUNC StoredFunc = (FUNC)_Func;

            std::function<void()> *pBindFunc = new std::function<void()>;
            *pBindFunc = std::bind(StoredFunc, _Args...);

            m_Queue.push(pBindFunc);
        }

        return true;
    };

    bool Exec()
    {
        while (!m_Queue.empty())
        {
            std::function<void()> *iFunc = new std::function<void()>;
            *iFunc = *m_Queue.back();

            (*iFunc)();

            m_Queue.pop();
        }

        return true;
    };
private:
    std::unordered_map<E_EVSYS_MSG, std::vector<void *>>        m_Callbacks;
    std::queue<std::function<void()> *>             m_Queue;
};

void SomeCallback(int n, float f)
{
    printf("void SomeCallback(int, float): %d %0.1f\n", n, f);
}

int main()
{
    CEventManager::GetInstance()->RegCallback(E_EVSYS_MSG::MATHSQRT, &SomeCallback);

    CEventManager::GetInstance()->CallEvent(E_EVSYS_MSG::MATHSQRT, 10, 10600.0f);
    CEventManager::GetInstance()->CallEvent(E_EVSYS_MSG::MATHSQRT, 12, 1.0f);

    CEventManager::GetInstance()->Exec();
    return 0;
}

输出是:

无效 SomeCallback(int, float): 12 1.0

无效 SomeCallback(int, float): 12 1.0


如果我换行:

CEventManager::GetInstance()->CallEvent(E_EVSYS_MSG::MATHSQRT, 12, 1.0f);
CEventManager::GetInstance()->CallEvent(E_EVSYS_MSG::MATHSQRT, 10, 10600.0f);

输出变成了这样:

无效 SomeCallback(int, float): 10 10600.0

无效 SomeCallback(int, float): 10 10600.0


调试器显示,m_Queue 中的所有数据都是正确的。

这意味着,队列中的数据是这样的:

第一个:func: void(int,float); 参数:12、1.0f;

第二:func:void(int,float);参数:10、10600.0f;


怎么了?哪里出错了?

PS我new std::function<void()>;只是为了尝试解决错误......

视觉工作室 2013(12.0.30..)

4

1 回答 1

2

您正在调用m_Queue.back()inExec而不是m_Queue.front()

bool Exec()
{
    while (!m_Queue.empty())
    {
        std::function<void()> *iFunc = new std::function<void()>;
        *iFunc = *m_Queue.back();

        (*iFunc)();

        m_Queue.pop();
    }

    return true;
}

这导致调用第二个存储函数两次,第一个存储函数调用零次。

于 2014-03-15T05:38:57.410 回答