基于数据实例化int模板
Instantiating int templates based on data
我使用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();
主要问题是主容器需要一个不透明的类。您仍然可以在后台保持类型安全,但是可读性会受到一些影响。
相关文章:
- 从C++实例化QML
- 设计一个只能由特定类实例化的类(如果可能的话,通过make_unique)
- 如何创建一个空的全局类并在启动时实例化它
- 在两个类中共享相同的函数调用,并在不需要时避免空实例化
- 约束和显式模板实例化
- 为什么包含windows.h会产生语法错误,从而阻止类的实例化?(C2146,C2065)
- 对象实例化调用构造函数的次数太多
- 如何使用非默认构造函数实例化模板化类
- 静态数据成员模板专用化的实例化点在哪里
- 错误的cv::face FacemarkLBF实例化
- 未定义模板'std::__1::function<int (double, double, double, double)>'的隐式实例化
- c++模板实例化可以使用int、long等,但不能使用float、double等
- 当我创建一个int指针并实例化一个数组时,数组在内存中发生了什么
- 使用向量<向量>成员实例化对象时的隔离错误<int>
- int&& 在模板实例化中有效吗?
- 避免使用int参数的模板类的C++爆炸性实例化
- 如何实例化 int 类型的数组对象并在 c++ 中填充它
- 为什么模板试图用'int&'而不是"int"进行实例化?
- 未定义模板 'std::__1::array<int, 3>' 的隐式实例化
- 基于数据实例化int模板