I am writing C++/Python hybrid. The library that glue the two parts support Eigen matrix/array but not tensor.
Is it safe to do something like this?
#include <iostream>
#include <Eigen/Eigen>
using namespace Eigen;
template<typename D>
auto f(DenseBase<D>& x, const Index i) {
// x2 is destroyed when the program leaves
// this function.
ArrayWrapper<D> x2(x.derived());
return x2.middleCols(i * 3, 3);
}
int main() {
ArrayXf a(3, 9);
a = 0;
f(x, 1) = 1;
std::cout << x << "\n";
}
Or, is it better to do this?
template<typename D>
auto f(DenseBase<D>& x, const Index i) {
return x.derived().array().middleCols(i * 3, 3);
}
Both version are the same, and both are safe. This is because proxy expressions like ArrayWrapper
or Block
as returned by middleCols()
are nested by value, not by reference.