如何将特征矩阵行引用(被视为向量)传递给另一个 .cpp 中实现的函数?
How pass Eigen matrix row reference (to be treated as a vector) to a func implemented in another .cpp?
希望你能帮助我。
我的问题源自另一个已回答的问题 here
在该页面内 rhashimoto 对类似问题给出了很好的答案:
#include <iostream>
#include <Eigen/Core>
template<typename V>
void set_row(V&& v) {
v = Eigen::Vector3f(4.0f, 5.0f, 6.0f);
}
int main() {
Eigen::Matrix3f m = Eigen::Matrix3f::Identity();
set_row(m.row(1));
std::cout << m;
return 0;
}
问题是当您需要将 set_row 函数放入另一个 cpp 文件时。 这样,编译器就会报未定义引用错误。
我找到了解决方法 here
他们说你可以解决的地方:
- 将 set_row 函数移动到头文件中。好的!我试过了,它有效,但我不喜欢它!或者
- 在 set_row 函数的 cpp 文件中显式实例化模板。这就是我会做的。我试了没成功。
你能告诉我如何实现最后一点吗?
最好使用 header 中的模板来完成。
如果您必须将它放在 CPP 文件中,您可以按照您的建议使用模板函数和显式实例化。关键是使用 Eigen Block
type.
#include <Eigen/Dense>
template <int N, int M>
void set_row(Eigen::Block<Eigen::Matrix<float, N, M>, 1, M> row) {
// Note: this implementation is not correct in the general case.
row = Eigen::Vector3f(4.0f, 5.0f, 6.0f);
}
// Explicit instantiation for fixed 3-by-3 case.
template void set_row(Eigen::Block<Eigen::Matrix<float, 3, 3>, 1, 3> row);
// Explicit instantiation for dynamic N by M case.
// Note that current implementation will not work.
template void set_row(Eigen::Block<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>, 1, Eigen::Dynamic> row);
工作神螺栓示例:https://godbolt.org/z/T4EYsc
希望你能帮助我。 我的问题源自另一个已回答的问题 here
在该页面内 rhashimoto 对类似问题给出了很好的答案:
#include <iostream>
#include <Eigen/Core>
template<typename V>
void set_row(V&& v) {
v = Eigen::Vector3f(4.0f, 5.0f, 6.0f);
}
int main() {
Eigen::Matrix3f m = Eigen::Matrix3f::Identity();
set_row(m.row(1));
std::cout << m;
return 0;
}
问题是当您需要将 set_row 函数放入另一个 cpp 文件时。 这样,编译器就会报未定义引用错误。 我找到了解决方法 here
他们说你可以解决的地方:
- 将 set_row 函数移动到头文件中。好的!我试过了,它有效,但我不喜欢它!或者
- 在 set_row 函数的 cpp 文件中显式实例化模板。这就是我会做的。我试了没成功。
你能告诉我如何实现最后一点吗?
最好使用 header 中的模板来完成。
如果您必须将它放在 CPP 文件中,您可以按照您的建议使用模板函数和显式实例化。关键是使用 Eigen Block
type.
#include <Eigen/Dense>
template <int N, int M>
void set_row(Eigen::Block<Eigen::Matrix<float, N, M>, 1, M> row) {
// Note: this implementation is not correct in the general case.
row = Eigen::Vector3f(4.0f, 5.0f, 6.0f);
}
// Explicit instantiation for fixed 3-by-3 case.
template void set_row(Eigen::Block<Eigen::Matrix<float, 3, 3>, 1, 3> row);
// Explicit instantiation for dynamic N by M case.
// Note that current implementation will not work.
template void set_row(Eigen::Block<Eigen::Matrix<float, Eigen::Dynamic, Eigen::Dynamic>, 1, Eigen::Dynamic> row);
工作神螺栓示例:https://godbolt.org/z/T4EYsc