gpt4 book ai didi

c++ - 使用 Eigen C++ 库进行模板编程时出现编译错误

转载 作者:行者123 更新时间:2023-11-30 01:56:32 26 4
gpt4 key购买 nike

我下载了 Eigen (3) 库并开始使用它。我写了一个模板函数,并在函数内部声明了一个“模板类型”的局部变量。我收到以下编译错误。


$ g++ EigenTest.cpp

EigenTest.cpp: In instantiation of ‘void myFunc(Eigen::MatrixBase<Derived>&) [with Type1 = Eigen::Matrix<double, -1, -1>]’:
EigenTest.cpp:24:10: required from here
EigenTest.cpp:16:26: error: conversion from ‘Eigen::DenseCoeffsBase<Eigen::Matrix<double, -1, -1>, 1>::Scalar {aka double}’ to non-scalar type ‘Eigen::Matrix<double, -1, -1>’ requested
Type1 tmp = matrix(0, 0);

“EigenTest.cpp”如下。


#include "Eigen/Dense"

#include <iostream>

template<typename Type1>
void myFunc(Eigen::MatrixBase<Type1>& matrix)
{
int i=matrix.rows();
Type1 tmp = matrix(0, 0); // getting compiler error here
std::cout<<"tmp is ->"<<tmp<<std::endl;
}

int main()
{
Eigen::MatrixXd m(2,2);
m.setConstant(100);
myFunc(m);
return 0;
}

我还尝试使用“typename Type1 tmp = matrix(0, 0);”
这也行不通!

如何解决这个问题?在普通的 C++ 模板编程中(没有 Eigen),我可以在模板函数中定义一个局部变量作为 'Type1 tmp;"

最佳答案

Eigen::MatrixBase<Type1> , Type1不是标量类型,而是实际表达式的类型。在您的示例中,它将是 MatrixXd,但如果调用 myFunc,例如 m.block(...),则 Type1将是一个 block <...>。要获取标量类型,可以使用 Type1::Scalar:

template<typename Type1>
void myFunc(Eigen::MatrixBase<Type1>& matrix)
{
typename Type1::Scalar Scalar;
Scalar tmp = matrix(0, 0);
}

如果您需要类似于 Type1 的矩阵类型, 使用 Type1::PlainObject ,例如:

typename Type1::PlainObject mat = 2 * matrix * matrix.transpose();

关于c++ - 使用 Eigen C++ 库进行模板编程时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19701977/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com