diff --git a/ReactCommon/utils/ContextContainer.h b/ReactCommon/utils/ContextContainer.h index b26f3106d..623de4be9 100644 --- a/ReactCommon/utils/ContextContainer.h +++ b/ReactCommon/utils/ContextContainer.h @@ -51,6 +51,7 @@ class ContextContainer final { /* * Returns a previously registered instance of the particular type `T` * for `key`. + * Throws an exception if the instance could not be found. */ template T getInstance(std::string const &key) const { @@ -65,6 +66,27 @@ class ContextContainer final { return *std::static_pointer_cast(instances_.at(key)); } + /* + * Returns a (wrapped in an optional) previously registered instance of + * the particular type `T` for given `key`. + * Returns an empty optional if the instance could not be found. + */ + template + better::optional findInstance(std::string const &key) const { + std::shared_lock lock(mutex_); + + auto iterator = instances_.find(key); + if (iterator == instances_.end()) { + return {}; + } + + assert( + typeHashes_.at(key) == typeid(T).hash_code() && + "ContextContainer stores an instance of different type for given key."); + + return *std::static_pointer_cast(iterator->second); + } + private: mutable better::shared_mutex mutex_; // Protected by mutex_`.