Reputation: 36649
I am using Eigen as a linear algebra package. There they have fixed size matrix types, defined something like:
template<class TNumber, size_t N, size_t M>
class Matrix
{...}
so becasue I am using only vectors and square matrices, most of my classes ended up being similar templates:
template<size_t K>
class MyClass {...}
The dimension K will actually depend on data loaded from a file. Is there any reasonable way to instantiate these templates with a dynamic size K, or do I have to have a switch statement:
switch(dim) {
case 1: MyClass<1>...
case 2: MyClass<2>...
default: //too much data
}
?
Upvotes: 0
Views: 95
Reputation: 2420
If you have an upper limit to the number of dimensions, you can create proxy classes to map the dimension to an index and use the index instead. That is not a pretty solution, but it might work.
class Proxy{
protected:
OpaqueAllocator *allocators[10];
public:
Proxy(){
allocators[0] = new SpecializedAllocator<0>();
allocators[1] = new SpecializedAllocator<1>();
allocators[...] = new SpecializedAllocator<...>();
allocators[9] = new SpecializedAllocator<9>();
}
static OpaqueAllocator* getAllocator(const size_t index){ return allocators[index]; }
};
// usage:
int test = 2;
// allocate a two dimensional array:
Container *c = Proxy::getAllocator(test)->allocate();
The main problem is that you need an opaque class for the main container. You can still preserve type safety in the background, but the readability will suffer a bit.
Upvotes: 0
Reputation: 62083
Templates are instantiated at compile time, not run time. Therefore, you can't have a template instantiation based on run-time data.
Upvotes: 1