mercredi 20 mars 2019

C++ (function) template that return its unique argument without copying it for certain types

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<double> value(SomeContainer<double> x) { return x; }
SomeContainer<double> value(SomeContainer<MyType> 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<double> value(Matrix<double>)
Matrix<double> value(Matrix<MyType>)

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?

Aucun commentaire:

Enregistrer un commentaire