There are two solutions. In Pre C ++ 11, you can write a template, for example:
template <typename T, typename U> struct WhatWillItBe { typedef T result_t; }; template <typename T> struct WhatWillItBe<T, double> { typedef double result_t; };
etc .. and write a lot of specializations, then you can use this to search for the return type, for example:
template <typename T, typename U> inline const Vector<typename WhatWillItBe<T,U>::result_t> operator*(const Vector<T>& vector, U scalar) { return Vector<typename WhatWillItBe<T,U>::result_t>(vector.x * scalar, vector.y * scalar); }
As an alternative, C ++ 11 makes this simple, you can write auto for the return type and use -> to indicate the type of the return value after the rest of the function:
template <typename T, typename U> inline auto operator*(const Vector<T>& vector, U scalar) -> Vector<decltype(vector.x*scalar)> { return Vector<decltype(vector.x*scalar)>(vector.x * scalar, vector.y * scalar); }
Which allows you to use decltype for the return type of the function, setting it based on what is natural for promotion using vector.x * scalar .
Flexo source share