3

I have a template class, MyClass<...>, which has member variables of type Eigen::Matrix<X, N, M> where X is the native template parameter for a particular instance of MyClass.

Assuming that my private variable of the aforementioned type is myVar. In order to make the setMyVar function generic, I define it as a template function like

  template <typename U>
  void setMyVar(const Eigen::Matrix<U, 3, 1>& newVal) const { 
     // myVar is of type Eigen::Matrix<T, 3, 1>
     myVar = newVal.cast<T>();
  }

My question is whether Eigen skips the casting operation in case T == U.

I am in particular interested in learning the behavior of Eigen in such a scenario. Otherwise I am very well aware of alternative solutions such as using SFINAE to force to compiler to choose among the right overloads of setMyVar or use if constexp (std::is_same_v<T, U) {...} else {...} (for c++17) to decide whether a cast is required or not during compile time.

Thanks

ozlsn
  • 144
  • 4
  • What is T? A template variable? I can't see typename T. – mfnx Aug 09 '19 at 15:05
  • 1
    If `U` and `T` are the same, `cast` is a NOP (i.e., just returns a reference to the original object). – chtz Aug 09 '19 at 15:07
  • @MFnx In case the matrix ```myVar``` is large, one would want to avoid casting due to the obvious reason that it will cause unnecessary extra burden to the cpu. Answer to your question is, I would expect ```cast``` to return ```newVal``` as is. You can assume ```T``` to be of floating point type. – ozlsn Aug 09 '19 at 15:07
  • @chtz, is it possible to point to the source code that handles this case? – ozlsn Aug 09 '19 at 15:08
  • @ozlsn if you have performance concerns, benchmark your code (with optimisation enabled). Any blind assumptions without mesurenment are futile. – Guillaume Racicot Aug 09 '19 at 15:09
  • Ah, I think I understand the question, you are asking if there are 2 copies or just one, or more clearly if there is an intermediate matrix. Even in the case of the cast, I do hope there isn't, that's the whole point of expression templates. – Marc Glisse Aug 09 '19 at 15:09
  • 2
    It is a bit scattered in the source. Maybe the important part is here: https://bitbucket.org/eigen/eigen/src/8071cda5714d7f/Eigen/src/Core/util/XprHelper.h#lines-514 – chtz Aug 09 '19 at 15:14
  • 3
    Hmm. I assume the line which writes ```typedef typename conditional::value, const XprType&,CastType>::type type;``` unveils the intend by setting the return type as ```XprType``` if input and output scalar types are the same. Thanks @chtz – ozlsn Aug 09 '19 at 15:24
  • 2
    @ozlsn if you find a good answer and want to help future readers, you are welcome to write an answer to your own question – alter_igel Aug 09 '19 at 18:33

0 Answers0