基于数据实例化int模板

Instantiating int templates based on data

本文关键字:实例化 int 模板 数据 于数据      更新时间:2023-10-16

我使用Eigen作为线性代数包。它们有固定大小的矩阵类型,定义如下:

template<class TNumber, size_t N, size_t M>
class Matrix
{...}

所以因为我只使用向量和方阵,我的大多数类最终都是类似的模板:

template<size_t K>
class MyClass {...}

维度K实际上取决于从文件中加载的数据。是否有任何合理的方法来实例化这些动态大小为K的模板,或者我必须有一个switch语句:

switch(dim) {
case 1: MyClass<1>...
case 2: MyClass<2>...
default: //too much data
}

?

模板在编译时实例化,而不是在运行时实例化。因此,您不能基于运行时数据进行模板实例化。

如果对维度数量有上限,则可以创建代理类将维度映射到索引并使用索引。这不是一个漂亮的解决方案,但它可能有效。

  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();

主要问题是主容器需要一个不透明的类。您仍然可以在后台保持类型安全,但是可读性会受到一些影响。