这特别是关于C ++库Eigen3
。我想让特定类型的矩阵的调用运算符重载,因为我经常遇到以下情况:
Eigen::MatrixXd A(N, N);
// Do stuff to fill A
auto matrix_index = std::pair<int,int>(5,6);
auto matrix_element = A(std::get<0>(matrix_index), std::get<1>(matrix_index));
如果您需要执行一次,这很好,但是很快就会变得麻烦。我想拥有的是
Eigen::MatrixXd A(N, N);
// Do stuff to fill A
auto matrix_index = std::pair<int,int>(5,6);
auto matrix_element = A(matrix_index);
为此,我需要将operator()
重载为Eigen::MatirxXd
,但我真的不知道该怎么做...我的幼稚方法是
double Eigen::MatrixXd::operator()(Eigen::MatrixXd const & A, std::pair<int,int> const & pair){
return A(std::get<0>(matrix_index), std::get<1>(matrix_index));
}
这没有用。查看the documentation,发现似乎有一个实现大多数运算符的基类。但是,即使这个基类也没有实现operator()
,即使实现了,我也不太了解如何重载它。
[我看到两种实现您想要的可能性的方法:使用Eigen的插件机制(如@chtz所建议的)重载operator()
和使用Eigen::TensorMap
接受索引作为std::array
(尽管不是std::pair
)。
1。本征的插件机制
该插件可能看起来像这样:
inline const Scalar &operator()(const std::pair<Index, Index> &indices) const {
return derived().coeffRef(indices.first, indices.second);
}
inline Scalar &operator()(const std::pair<Index, Index> &indices) {
return derived().coeffRef(indices.first, indices.second);
}
2。使用TensorMap
类似以下内容也可以:
Eigen::MatrixXf mat(4,4);
mat << 0, 1, 2, 3,
4, 5, 6, 7,
8, 9, 10, 11,
12, 13, 14, 15;
auto indices = std::array<Eigen::Index, 2>{1, 1};
float coeff = Eigen::TensorMap<Eigen::Tensor<float, 2>>(mat.data(), 4, 4)(indices);
auto coeff = mat(); // 5