Reputation: 140
It's event manager, which work principle shown in the main(). So, the code:
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;
}
And the output is:
void SomeCallback(int, float): 12 1.0
void SomeCallback(int, float): 12 1.0
If I swap lines:
CEventManager::GetInstance()->CallEvent(E_EVSYS_MSG::MATHSQRT, 12, 1.0f);
CEventManager::GetInstance()->CallEvent(E_EVSYS_MSG::MATHSQRT, 10, 10600.0f);
The output became like this:
void SomeCallback(int, float): 10 10600.0
void SomeCallback(int, float): 10 10600.0
Debugger shows, that in m_Queue all data is right.
It means, that in queue data is like this:
first: func: void(int,float); params: 12, 1.0f;
second: func: void(int,float); params: 10, 10600.0f;
What's wrong? Where's error?
P.S. I do new std::function<void()>;
just to try to resolve the bug...
Visual Studio 2013(12.0.30..)
Upvotes: 0
Views: 141
Reputation: 42554
You are invoking m_Queue.back()
in Exec
instead of 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;
}
which results in invoking the second stored function twice, and the first stored function zero times.
Upvotes: 2