This forum has been archived. All content is frozen. Please use KDE Discuss instead.

Templatized Ref

Tags: None
(comma "," separated)
alejandrocastro
Registered Member
Posts
15
Karma
0
OS

Templatized Ref

Wed Jun 22, 2016 4:41 pm
I write the following method:

Code: Select all

template<class T>
void foo_nonconst(Ref<Matrix<T, 3, 1>> q) {
  std::cout << __PRETTY_FUNCTION__ << std::endl;
  for(int i = 0; i < q.size(); ++i) {
    std::cout<< q(i) << " ";
  }
  std::cout << std::endl;
}


I know it'd work if instead of Matrix<T, 3, 1> I had, for instance, Vector3d. However I'd like to have the method templatized on the scalar type only. The method should work with any kind of vector that is contiguous in memory either a Matrix<T, 3, 1>, a block or a map.

However when trying to pass a Vector3d to the previous method I get a compile error like so:

Code: Select all
Scanning dependencies of target EigenRef
[ 50%] Building CXX object CMakeFiles/EigenRef.dir/eigen_ref_test.cc.o
./EigenRef/eigen_ref_test.cc: In function ‘int main()’:
./EigenRef/eigen_ref_test.cc:56:17: error: no matching function for call to ‘foo_nonconst(Eigen::Vector3d&)’
   foo_nonconst(q);
                 ^
./EigenRef/eigen_ref_test.cc:56:17: note: candidate is:
./EigenRef/eigen_ref_test.cc:26:6: note: template<class T> void foo_nonconst(Eigen::Ref<Eigen::Matrix<T, 3, 1> >)
 void foo_nonconst(Ref<Matrix<T, 3, 1>> q) {
      ^
./EigenRef/eigen_ref_test.cc:26:6: note:   template argument deduction/substitution failed:
./EigenRef/eigen_ref_test.cc:56:17: note:   ‘Eigen::Matrix<double, 3, 1>’ is not derived from ‘Eigen::Ref<Eigen::Matrix<T, 3, 1> >’
   foo_nonconst(q);
                 ^
make[3]: *** [CMakeFiles/EigenRef.dir/eigen_ref_test.cc.o] Error 1
make[2]: *** [CMakeFiles/EigenRef.dir/all] Error 2
make[1]: *** [CMakeFiles/EigenRef.dir/rule] Error 2
make: *** [EigenRef] Error 2


why doesn't this code compile? is there a way to accomplish this without using MatrixBase? (for my application I do know these arguments will be contiguous in memory but I'd like to explicit instantiate my method and the number of options increases very rapidly!)

Thank you in advance.
User avatar
ggael
Moderator
Posts
3447
Karma
19
OS

Re: Templatized Ref

Wed Jun 22, 2016 8:05 pm
This cannot compile because template deduction with type conversion only works for static casts to a base class. So:
- MatrixXd -> MatrixBase<Derived> : OK
- MatrixXd -> Ref<Matrix<T> > : not OK

Ref has been especially designed to enable some level of genericity without having to rely on template. So in your case better use a generic MatrixBase<Derived> with a static assertion on the sizes.
alejandrocastro
Registered Member
Posts
15
Karma
0
OS

Re: Templatized Ref

Fri Aug 12, 2016 8:22 pm
I realized I never replied to this. Thank you ggael for your prompt response.


Bookmarks



Who is online

Registered users: Bing [Bot], blue_bullet, Google [Bot], rockscient, Yahoo [Bot]