我正在编写模板函数,它应该以一些Eigen::MatrixBase<Derived>作为输入,执行一些计算,然后返回新的特征值。我希望返回与输入具有相同存储顺序的值。
但我不知道如何从Eigen::MatrixBase<Derived>获得存储订单。在这种情况下,我能做些什么,这有可能吗?我知道我可以将存储顺序作为另一个模板参数传递,或者接收Eigen::Matrix<InpScalar, InpStatRows, InpStatCols, InpStorageOrder>,但如果可能的话,我希望避免它。
为我糟糕的英语道歉
发布于 2019-12-05 13:06:11
要查看MatrixBase<Derived>的存储顺序,可以检查IsRowMajor枚举:
int const StorageOrder = Derived::IsRowMajor ? Eigen::RowMajor : Eigen::ColMajor;如果希望具有与Derived相同的存储顺序和大小的类型,可以直接使用typename Derived::PlainObject (或PlainMatrix):
template<class Derived>
typename Derived::PlainObject foo(const Eigen::MatrixBase<Derived> & input)
{
typename Derived::PlainObject return_value;
// do some complicated calculations
return return_value;
}发布于 2019-12-05 10:03:09
要响应您对如何声明接收通用矩阵的函数的评论,您可以这样做:
因为函数(和方法)从它们的实际函数参数推断它们的模板参数,如下所示
template <typename InpScalar, int InpStatRows, int InpStatCols, int InpStorageOrder>
void foo(Eigen::Matrix<InpScalar, InpStatRows, InpStatCols, InpStorageOrder>& matrix)
{
//you can utilize InpStorageOrder here
}matrix输入参数的模板参数将自动推导,这意味着您不必在调用函数时显式地指定它们,只需传递任何Eigen::Matrix
关于如何从另一个函数调用函数的示例
void bar()
{
Eigen::Matrix<double, 3, 3, Eigen::RowMajor> mat;
foo(mat);
}如果您只想获得给定的矩阵的存储顺序,如果Eigen库中没有任何东西可以这样做,那么您可以为本征矩阵实现一个类型特征。
template <typename TMatrix>
struct MatrixTraits {};
//Partial specialization of MatrixTraits class template
//will accept only `Eigen::Matrix` classes as its template argument
template <typename InpScalar, int InpStatRows, int InpStatCols, int InpStorageOrder>
struct MatrixTraits<Eigen::Matrix<InpScalar, InpStatRows, InpStatCols, InpStorageOrder>>
{
int StorageOrder = InpStorageOrder;
};要利用这一点,您可以这样做:
void bar()
{
Eigen::Matrix<double, 3, 3, Eigen::RowMajor> mat;
int StorageOrder = MatrixTraits<decltype(mat)>::StorageOrder;
}https://stackoverflow.com/questions/59191801
复制相似问题