c++ - Safe way of casting void* to something higher? -



c++ - Safe way of casting void* to something higher? -

i've got generic class manages resources of kinds of types, since don't want create instance of resourcemanager every t there (thus having 1 resource manager each type t), have create type of t unknown resourcemanager class.

i saving map of void* pointers , converting them required format if requests type out of templated load() method;

template <typename t> t* load(const std::string &location) { //do stuff here //everybody take cover!!! homecoming static_cast<t*>(m_resources[location]); }

i utilize template specialization introduce different loaders class:

template<> awesometype* load(const std::string &location) { //etc. homecoming static_cast<awesometype*>(m_resources[location]); }

i aware ugly, there no way around right now. introduce static maps in within of specialized load methods, way can't bind lifetime of resources lifetime of resourcemanager object, essential feature.

but since unsafe (since void* pointers can anything), i'd @ to the lowest degree check @ runtime if conversion going work, can react without having application crash.

how can this?

you can this, if extend saved value type - create struct saves type_info object:

#include <type_info> struct resourceinfo { std::type_info const& info; void* ptr; }; // ... // give general thought template<class res> void cacheresource(std::string const& location, res* res) { resourceinfo ri = { typeid(res), res }; m_resources.insert(std::make_pair(location, ri)); } template<class res> res* load(std::string const& location) { map_type::const_iterator res_it = m_resources.find(location); if(res_it != m_resources.end()) { if(typeid(res) != res_it->second.info) { throw sorrybuddywrongresourcetype(some_info_here); } homecoming static_cast<res*>(res_it->second.ptr); } }

this similar how it, utilize shared_ptr<void> save resources.

c++ void-pointers

Comments

Popular posts from this blog

iphone - Dismissing a UIAlertView -

c# - Can ProtoBuf-Net deserialize to a flat class? -

javascript - Change element in each JQuery tab to dynamically generated colors -