【发布时间】:2020-08-22 09:20:11
【问题描述】:
假设我有一个用于矩阵的 CRTP 模板类
template<class T, class Derived>
class MatrixBase{
private:
//...
public:
Derived some_function(const Derived &other){
Derived& self = (Derived&)*this; // In my application I cant use static_cast.
// Some calculations..., which will determine the below
// defined variables "some_number_of_rows" and "some_number_of_cols"
// If Derived = DynamicMatrix<T>, then result should be declared as:
DynamicMatrix<T> result(some_number_of_rows, some_number_of_cols);
// while if Derived = StaticMatrix<T, Rows, Cols>, then result should be declared as:
StaticMatrix<T, some_number_of_rows, some_number_of_cols> result;
// Perform some more calculations...
return result;
}
};
template<class T>
class DynamicMatrix{
private:
size_t n_rows, n_cols;
T *data;
public:
DynamicMatrix(const size_t n_rows, const size_t n_cols);
// ...
};
template<class T, int Rows, int Cols>
class StaticMatrix{
private:
size_t n_rows = Rows, n_cols = Cols;
T data[Rows * Cols];
public:
StaticMatrix() {}
// ...
};
如何检查MatrixBase::some_function(const Derived &other) 中的派生类类型以在两个派生类中使用此基函数?,从而避免在这些类中分别重新定义/覆盖/代码重复。在这种情况下,基本上只有result 矩阵的声明需要我检查派生类类型,因为声明是不同的,具体取决于它是固定大小的矩阵还是动态矩阵。也欢迎使用除类型检查之外的其他解决方案。
注意:由于我的应用程序的性质,我无法使用标准功能。
编辑:示例函数中的some_number_of_rows 和some_number_of_cols 通常不是constexpr,因为它们取决于对象矩阵的函数和大小。例如,对于 transpose 函数,结果的维度必须为 <Derived.n_cols, Derived.n_rows,而对于按列的点积,则为 <1, Derived.n_cols>。
【问题讨论】:
-
some_number_of_rows和some_number_of_cols来自哪里?来自&other? -
“一些计算...,这将确定 [..]
some_number_of_rows和some_number_of_cols”。对于StaticMatrix,这些应该是constexpr,DynamicMatrix怎么样? -
哦,是的,我的错。