Boost logo

Ublas :

Subject: [ublas] Returning vectors or matrices from user functions
From: Mark Johnson (mj1_at_[hidden])
Date: 2009-09-09 12:15:23


Thanks Jesse for your helpful advice with this. The Curiously Recurring
Template Pattern is very clever!

I also have two further questions -- what types should one use in user
functions that will either return a vector or a matrix, and what types
should one use for arguments to functions that will mutate a vector or
matrix in place?

For function return values, the main issue is how to specify the return
type to avoid needless copying, I think. Would it be reasonable to
return a vector_expression or a const vector_expression, for example? I
think this would be safe if these referred to vectors or matrices that
are instantiated in the function call. But perhaps it's also possible
that a modern compiler would optimize away the unnecessary copy
operations even if one returns ordinary vectors or matrices?

For function arguments that will be modified in place, I think the issue
is whether there is a way to define the types so that non-const vector
expressions can be conveniently passed to the function.

To give an artificially simple example, suppose I need to normalize each
row in a matrix m (i.e., scale the entries so that the sum of the values
in each row is one). One way to do this is to write a "my_normalize"
function that operates on a single vector, and then call that function
on each row of the matrix m, i.e., my_normalize(row(m, i)).

But this generates compiler errors if my_normalize takes a non-const
reference argument, as I'm trying to pass a non-const reference to the
temporary vector proxy (i.e., the object returned by row(m,i)). Again,
I'm not sure what the best thing to do here is. Perhaps I should pass
the argument to my_normalize by value? But then if I call my_normalize
with a regular vector as its argument, then it makes a copy of its
argument and therefore fails to mutate that argument.

Thanks again for you help,

Mark