As far as you use one of the two types of template, you run the risk of invoking the result of the result. As an example, if you accidentally choose int as the target type, although the total amount is float , it will be reset to the selected type.
In any case, starting with C ++ 11, you rely on the decltype , as in the example above (or at least you can do this if Container::T and Container::U are types for which + )
I also used the auto specifier as the return value for operator+ , since it is at our disposal since C ++ 14, and it is really really useful.
This follows the above working example:
#include <iostream> #include <vector> template<typename T> struct Container { T value; Container(const T& value) : value(value) { } }; template<typename T, typename U> auto operator+(const Container<T>& lhs, const Container<U>& rhs) { return Container<decltype(lhs.value+rhs.value)>{lhs.value + rhs.value}; } int main() { Container<int> c1{1}; Container<float> c2{0.5}; std::cout << (c1+c2).value << std::endl; }
source share