使用模板化特征矩阵初始化

class using templated eigen matrix

本文关键字:初始化 特征      更新时间:2023-10-16

我写了一个类

class abc
{
public:
    template <typename Derived >
    abc( const Eigen::MatrixBase < Derived > &matA,
         const Eigen::MatrixBase < Derived > &matB,
         Eigen::MatrixBase < Derived > &matC );
};
template <typename Derived >
abc::abc( const Eigen::MatrixBase < Derived > &matA,
          const Eigen::MatrixBase < Derived > &matB,
          Eigen::MatrixBase < Derived > &matC )
{
    matC.derived().resize( matA.rows(), matA.cols() );
    for( int r = 0; r < matA.rows(); r++ )
    {
        for( int c = 0; c < matA.cols(); c++ )
        {
            matC(r,c) = log( matA(r,c) )/log( matB(r,c) );
        }
    }
}

,但在main中使用类ABC时我得到未定义的引用错误

typedef Eigen::Matrix< float, Eigen::Dynamic, Eigen::Dynamic > Matrix_Float;
main()
{
Matrix_Float matA, matB, matC;
// put values in matA, matB
    abc cls_abc( matA, matB, matC );
}

错误错误:对' abc::abc <特征:矩阵&>>(特征:MatrixBase & lt;特征:矩阵& lt;float, -1, -1, 0, -1, -1>> constent &, Eigen::MatrixBase <特征:矩阵&>> constent &, Eigen::MatrixBase <特征:矩阵&>> &)'

类定义的语法有什么问题吗?

请帮助。

你有几个问题。首先,对于模板类,您需要在声明中提供实现(即在.h文件中,而不是在.cpp文件中)。其次,您希望类被模板化,请注意构造函数。第三,当使用模板化类时,需要指定模板形参。

把所有这些放在一起,你的类(.h)文件应该像这样:
template <typename Derived > class abc  // Template the class
{
public:
    //template <class Derived > // Don't put this here, but above
    abc(
        const Eigen::MatrixBase < Derived > &matA,
        const Eigen::MatrixBase < Derived > &matB,
        Eigen::MatrixBase < Derived > &matC);
};
template <typename Derived >
abc<Derived>::abc(
    const Eigen::MatrixBase < Derived > &matA,
    const Eigen::MatrixBase < Derived > &matB,
    Eigen::MatrixBase < Derived > &matC)
{
    matC.derived().resize(matA.rows(), matA.cols());
    for (int r = 0; r < matA.rows(); r++)
    {
        for (int c = 0; c < matA.cols(); c++)
        {
            matC(r, c) = log(matA(r, c)) / log(matB(r, c));
        }
    }
}

和您的main()应该看起来像:

int main(int argc, char* argv[]) // just "main()" is so passé
{
    Matrix_Float matA, matB, matC;
    // put values in matA, matB
    abc<Matrix_Float> cls_abc(matA, matB, matC);
}