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

Generic functions for modifying lvalues and rvalue Blocks?

Tags: None
(comma "," separated)
eacousineau
Registered Member
Posts
15
Karma
0
OS
Is there a way to write functions that can generically take non-const references to lvalues (MatrixBase<Derived>&) as well as references to rvalue blocks (i.e., MatrixBase<Derived>::RowXpr)?

I am working in c++0x and tried using &&, but I got an error about not being able to bind an lvalue to the rvalue reference... Might need to read up more on that.

A simple test case:
Code: Select all
template<typename Derived>
void stuff(MatrixBase<Derived> &X)
{
   cout << "[" << X.size() << "] " << X << endl;
   if (X.size() > 0)
      X(0) = 5.;
}

int main()
{
   MatrixXd X(2, 1);
   X << 1, 2;

   // Just fine
   stuff(X);

   // This works
   MatrixXd::RowXpr row = X.row(1);
   stuff(row);

   // This does not
   // stuff(X.row(1));

   cout << endl << X << endl;

   return 0;
}
Hauke
Registered Member
Posts
109
Karma
3
OS
Hi,

in C++ rvalues do not bind to mutable references. Changing your function to

Code: Select all
template <typename MatrixExpression>
void stuff(MatrixExpression&& X)

  typedef typename std::remove_reference<decltype(X.derived())>::type Derived;
  static_assert( std::is_base_of< MatrixBase<Derived>, typename std::remove_reference<MatrixExpression>::type >::value, "Need a MatrixBase!");

   cout << "[" << X.size() << "] " << X << endl;
   if (X.size() > 0)
      X(0) = 5.;
}


works as expected. I have to admit, that I do not quite get why MatrixBase<Derived>&& did not work but it is at least a workaround.

Regards,
Hauke
eacousineau
Registered Member
Posts
15
Karma
0
OS
Cool, thank you for the workaround!
I've posted the code on GitHub: https://github.com/eacousineau/eigen_cpp0x

[And I apologize for the lag-time in response!]


Bookmarks



Who is online

Registered users: Bing [Bot], claydoh, Google [Bot], rblackwell, Yahoo [Bot]