c++ - Templates and dependency injection -


i have class template resourcemanager , intended used this:

resourcemanager<image>* rm =     resourcemanager<image>::instance();  image* img = rm->acquire("picture.jpg"); rm->release(img); 

i'd use dependency injection (pass resourcemanager parameter functions supposed use instead of having used globally), given it's template don't know how this. have suggestions?

my game @ beginning of development , have 4 resource types (image, font, animation , sound) making single resourcemanager (i.e. not template) acquire function each type of resource not option.


edit: clarifications.

what i'm looking not how dependency injection one type of resourcemanager, of them @ once.

my gamestate objects need load resources when initialized/opened; through resourcemanagers. however, gamestates may need load number of types of resources: animations, fonts, images, sounds, etc — that's lot of function parameters each kind of resourcemanager! suggest do?

well, if function needs particular kind of resource (most will, probably), define specific template instance parameter:

function(resourcemanager<image> *rm, ...); 

if function needs kind of resource can either

  1. be template itself, like:

    template <typename t> function(resourcemanager<t> *rm, ...); 

    it need refer resource obtained resource manager, need template argument in more places anyway.

  2. use polymorphic base class. mean you'd have define like

    class resourcemanagerbase { /* methods need call via base class */ }; template <typename t> class resourcemanager : resourcemanagerbase { ... };  function(resourcemanagerbase *rm, ...) 

    the function can call methods defined in base class. if methods depend on resource-type internally, declared abstract virtual (virtual returntype method(...) = 0) in base , defined in template class itself. can use dynamic_cast check particular instantiation of resourcemanager you've got.

    note, if function needs refer resource, need resourcebase abstract base class of resources, can refer kind of resource.

the choice matter of trade-off between faster large code template function (the function compiled each specialization separately) or slower smaller code virtual methods (call virtual method slower, there no code duplication). template variant compile slower, because compilers generate code each object file uses , merge identical copies @ link time.


Comments

Popular posts from this blog

php - What is the difference between $_SERVER['PATH_INFO'] and $_SERVER['ORIG_PATH_INFO']? -

fortran - Function return type mismatch -

queue - mq_receive: message too long -