lundi 1 avril 2019

C++ unknown return type of template functions, code repetition when using decltype

In my job there are several template mathematical classes (e.g matrix)

an object can be implemented using either floats or doubles (or other numerical types but for this matter it doesn't really matter)

a double object can only interact with another double object. for this matter the function convert() was implemented for various types, with implementation similar to this:

Matrix<T2> convert(const Matrix<T1>& m, T2 dummy) {
   // create a matrix with type T2 and cast m values into it 
   //  retMatrix(i, j) = (T2)m(i,j)
} 

then you would call it with:

auto floatMatrix = convert(doubleMatrix, 0.f);

or the slightly more verbose:

auto floatMatrix = convert(doubleMatrix, float());

i want to add a function like the one below that will enable a cleaner (IMHO) way to call these functions

template <typename T, typename S>
auto convert(S&& s) -> decltype(convert(s, T())) {
  return convert(s, T());
} 

now they can be called using

auto floatMatrix = convert<float>(doubleMatrix);

my question is that my function signature is pretty awkward, I need to repeat the convert(s, T()) both in the decltype and in the actual function body

how do I overcome this?

thanks

edit:

currently we are not using c++14

Aucun commentaire:

Enregistrer un commentaire