In this exercise I am using Visual Studio 2017 and a modified version of the std_lib_facilities header found here.
Chapter 19 // Exercise 7
Try your solution to exercise 2 with some Numbers.
This one got me until I managed to find this post:
I then understood that I was trying to return a variable that was a common type between the two given template types. The compiler doesn't know that Number<int> and Number<double> are common types but Number does have ways to add themselves together and return a common type.
There is a way to define a common_type for user defined classes:
I used this to create common types for the combinations given in the exercise. It was working...in odd ways. I did some more testing and found my Number class broke spectacularly when doing Number<char> operations with any other type of number.
It took me a while to realise it was because when assigning, it created a copy of the Number<type> with whatever type was the first operand. So for example:
I eventually found a fix for this by setting the return type of the operator overload to a common type between the two of them:
It looks hideous. I could get rid of some of the ugliness with a typedef but I left it this way for "clarity". The only problem with this, is that all combinations of common types must be declared for the class.
No comments:
Post a Comment