How can a templated "ResourceCache" load/create resources of type T, if they require different creation parameters/methods?

I just dont know how to do it..

Basically, if each template specialization type (T) have different parameters for its initialization, how can a generalized ResourceCache load/create a resource?

template< class T>
class ResourceCache{

  T* cache[100];

  T* LoadResource(different parameters for different  T  ){//used in a cache miss..

          Create( different parameters for different  T );

  }
}

If I use abstraction for, i.e., a IResourceParams class, my ResourceCache will not be able to use its own known type resource data without using polymorphism, its kinda stupid, since at runtime he knows what the type is, id be tottaly doing shit at runtime in prol of a compile time facility...I guess..

On my current try I created a templated IResourceDesc that have a virtual T* Create() method, so you need to derive for add data and specialize the Create method, but it sucks, because I cant have a collection of IResourceDesc in the ResourceCache class ( for comparing current loaded ones, acquiring cached resources by desc, etc)...

Answers


In C++11, this is rather easy with a variadic template and perfect-forwarding:

#include <utility>

template<class... Args>
T* LoadResource(Args&&... args){
  unsigned dest_index = /* pick it */ 0;
  cache[dest_index] = new T(std::forward<Args>(args)...);
  return cache[dest_index];
}

For C++03, either provide ~10 overloads with different number of parameters or go for the in-place factory style:

template< class T>
class ResourceCache{
  T* cache[100];

  template<class Factory>
  T* LoadResource(Factory const& f){
    unsigned dest_index = /* pick cache slot */ 0;
    void* dest = operator new(sizeof(T));
    cache[dest_index] = f.construct(dest);
    return cache[dest_index];
  }
}

template<class T, class A1>
struct in_place_factory1{
  in_place_factory1(A1 const& a1) : _arg1(a1) {}
  int* construct(void* dest) const{
    return new (dest) T(_arg1);
  }
private:
  A1 const& _arg1; // make sure the original argument outlives the factory
};

// in code
ResourceCache<int> cache;
int arg = 5;
int* res = cache.LoadResource(in_place_factory1<int,int>(arg));

In-place factories are basically an inferior version of perfect-forwarding variadic template functions that can emplace the object directly into the containers storage without requiring an already complete object for a copy.


Need Your Help

How can I filter specifically for certain months if the days are not the same in each year?

r date filter

This is probably a very simple question that has been asked already but..

Check if the character is the VERY LAST one in my string?

python python-3.x

sorry if this is a duplicate, but I haven't found any clear answer out there.