I have a function value(x) which is overloaded for many types such that:
double value(double x) { return x; }
double value(MyType x) { return x.value(); }
SomeContainer value(SomeContainer x) { return x; }
SomeContainer value(SomeContainer x) { ... }
where MyType is actually a number with a gradient vector with respect to a set of parameters.
for use in generic (template) programs.
I want to define:
Matrix value(Matrix)
Matrix value(Matrix)
I am using Eigen matrices and this is my current implementation of the first function:
template < typename Derived,
typename std::enable_if< std::is_floating_point< typename Derived::Scalar >::value, int >::type = 0 >
Derived value( const Eigen::MatrixBase< Derived >& matrix )
{
return matrix;
}
The problem is that this seems inefficient unless in possible cases where the compiler can figure out that the result/argument are not being modified and elude the copy. I also cannot return a reference to the argument since it is a local/temporary.
Basically what I would like is for value(x) to be compiled as the argument expression itself if the argument is a Matrix of double/float. I don't see how I can achieve this with a function template and a macro would not allow for specialization.
What could be done to avoid the copy?
EDIT March 22, 2019:
If I replace the return type by
const Derived &
I get the following GCC warning:
warning: returning reference to temporary [-Wreturn-local-addr]
in the following code:
Matrix33 m;
m << 1, 2, 3,
4, 5, 6,
7, 8, 9;
std::cout << m << std::endl;
std::cout << value(m) << std::endl;
and the value(m) printout is garbage.
Also I am now thinking more and more this would be a bad idea to "return the object itself" because it is going to be used in generic code:
auto m = value(Mx)
where Mx is a Matrix of X (template parameter) and m is a double matrix.
Having different semantics (stealing the object in case X is double and creating a separate object in other cases) could lead to many programming mistakes.
Another possibility would be to return proxy objects.
The best however would be for the compiler to see when a copy is not needed because nothing is being changed. However this does not seem to be the case: my benchmark to compare
Matrix<double,3,3> M = ...
norm(M)
and
Matrix M = ...
norm(value(M))
shows that the second is a bit slower in a release (optimised) build.
JavaScript questions and answers, JavaScript questions pdf, JavaScript question bank, JavaScript questions and answers pdf, mcq on JavaScript pdf, JavaScript questions and solutions, JavaScript mcq Test , Interview JavaScript questions, JavaScript Questions for Interview, JavaScript MCQ (Multiple Choice Questions)