CmAsyncOp.h 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #pragma once
  2. #include "CmPrerequisitesUtil.h"
  3. #include "boost/any.hpp"
  4. namespace CamelotEngine
  5. {
  6. /**
  7. * @brief Asynchronous operation. Contains uninitialized data until
  8. * isResolved returns true.
  9. *
  10. * @note You are allowed (and meant to) to copy this by value.
  11. */
  12. class AsyncOp
  13. {
  14. private:
  15. struct AsyncOpData
  16. {
  17. AsyncOpData()
  18. :mIsCompleted(false)
  19. { }
  20. boost::any mReturnValue;
  21. bool mIsCompleted;
  22. };
  23. public:
  24. AsyncOp()
  25. :mData(new AsyncOpData())
  26. {}
  27. /**
  28. * @brief True if the async operation has completed.
  29. */
  30. bool hasCompleted() const { return mData->mIsCompleted; }
  31. /**
  32. * @brief Mark the async operation as completed.
  33. */
  34. void completeOperation(boost::any returnValue) { mData->mReturnValue = returnValue; mData->mIsCompleted = true; }
  35. /**
  36. * @brief Mark the async operation as completed, without setting a return value;
  37. */
  38. void completeOperation() { mData->mIsCompleted = true; }
  39. /**
  40. * @brief Retrieves the value returned by the async operation.
  41. */
  42. template <typename T>
  43. T getReturnValue() const
  44. {
  45. #if CM_DEBUG_MODE
  46. if(!hasCompleted())
  47. CM_EXCEPT(InternalErrorException, "Trying to get AsyncOp return value but the operation hasn't completed.");
  48. #endif
  49. // Be careful if boost returns bad_any_cast. It doesn't support casting of polymorphic types. Provided and returned
  50. // types must be EXACT. (You'll have to cast the data yourself when completing the operation)
  51. return boost::any_cast<T>(mData->mReturnValue);
  52. }
  53. private:
  54. std::shared_ptr<AsyncOpData> mData;
  55. };
  56. }