How to promote two types of patterns for arithmetic operations, such as built-in types?

If I have a general structure / class:

template<typename T> struct Container { T value; Container(const Value& value) : value(value) { } }; 

And I want to perform an operation on two of them:

 template<typename T, typename U> Container<T> operator+(const Container<T>& lhs, const Container<U>& rhs) { return Container<T>(lhs.value + rhs.value); } 

The problem is that if lhs is of type Container<int> and rhs is of type Container<float> , then I will get Container<int> back. But if I did auto result = 2 + 2.0f , then result would be of type float . Therefore, the behavior is incompatible between built-in types and custom types.

So, how would I take operator+ overload and return it Container<float> , similar to how C ++ handles arithmetic advancement with built-in types?

+5
source share
1 answer

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; } 
+5
source

Source: https://habr.com/ru/post/1234445/


All Articles