type_id_t - m1keall1son/ofxMediaSystem GitHub Wiki
ofxMediaSystem uses an simple method for converting types to something that can be used as a std::map
key. This mechanic is used by many of the underlying subsystems. type_id_t
is an aliased void pointer address and ms::type_id<typename T>
is a templated static void function. So at runtime each type gets a generated unique address that is hashable, comparable and can be treated as a value at runtime (though it is not suitable for compile-time expressions). Technically, this same thing could have been implemented using RTTI typeid()
, but this feature will work regardless of whether or not RTTI is enabled.
//gcc requires the address-of operator for comparisons
assert(&type_id<MyType> == &type_id<MyType>);
assert(&type_id<MyType> != &type_id<OtherType>);
//hold generic pointers to specific types
auto genericMap = std::map<type_id_t, std::shared_ptr<void>>();
auto myType = std::make_shared<MyType>(...);
auto generic = std::static_pointer_cast<void>(myType);
genericMap.emplace(type_id<MyType>, std::move(generic));
auto found = genericMap.find(type_id<MyType>);
if(found != genericMap.end()){
//We found it!
auto myType = std::static_pointer_cast<MyType>(found->second);
}
//hold generic factory functions
auto genericFactoryMap = std::map<type_id_t, std::function<std::shared_ptr<void>()>>();
genericMap[type_id<MyType>] = [](){
auto myType = std::make_shared<MyType>();
return std::static_pointer_cast<void>(myType);
};
auto generic = genericFactoryMap[type_id<MyType>]();
auto myType = std::static_pointer_cast<MyType>(generic);