1
votes

Best practices for writing functions taking Eigen matrices/arrays are very well documented here. But I am interested in how to do the same for Eigen::Tensor objects and expressions.

More specifically I want to write generic templated functions which takes tensor objects or expression as parameters while doing some operation on them (including resize/modification).

I tried using TensorBase<> as the function parameter, e.g:

template<class Derived, int AccessLevel>
void myRankAgnosticFunc(Eigen::TensorBase<Derived, AccessLevel >& tensor) {
  ...
  tensor.derived().resize(...); // Doesn't work since derived() is private
  ....
}

However unlike, Eigen::MatrixBase derived() is protected, and cannot be used.

Any suggestions as to how to write generic templated functions with Eigen::Tensor objects?

2

2 Answers

1
votes

I have no idea why derived() is protected in TensorBase. As a workaround you can cast to Derived& yourself like so:

Derived& tensr = static_cast<Derived&>(tensor);
// ...
tensr.resize(...);
0
votes

Why don't you simply pass the tensor type as a template argument ?

template<class MyTensor>
void myRankAgnosticFunc(MyTensor& tensor) {
  ...
  tensor.resize(...);
  ...

}