开发者

can return type mix? or workaround solution

开发者 https://www.devze.com 2023-03-02 18:15 出处:网络
I have a Fraction class, works fine within its own yard, like 1/2+1/3=5/6 or even with int,1/2+2=5/2.

I have a Fraction class, works fine within its own yard, like 1/2+1/3=5/6 or even with int,1/2+2=5/2.

It is okay for me to开发者_如何转开发 see 3/2+3/2=3/1, however, is there a way to return a type conditioned? For example, if the denominator is 1, it returns an int, otherwise returns a Fraction.

If not possible, any other detour?

class Fraction{
__int64 _num,_dem;
public:
    friend Fraction const operator+(Fraction const& lhs,Fraction const& rhs);
}

Fraction const operator+(Fraction const& lhs,Fraction const& rhs){
    return Fraction(lhs)+=rhs;
}

thanks a lot for any advice!


You can't conditionally change the return type. (You could have polymorphism if you had a super class, but that's not what you're asking for here since int is an intrinsic type.) Consider this case:

Fraction A, B;
//  initialize to 3/2 and 3/2
sometype C = A + B;

What is the type of C? The compiler must know. Even in cases of polymorphism or type inference, there must be a deterministic solution at compile time as to what the type of C is.

And there's no way to know whether the Fraction represents a whole number until runtime.


No, it's not possible in C++ to have the return type depend on the values of the operands in the way you're hoping for. What would be the point anyway, since the next layer of code out from there will need to know statically what the result type is?

Now, if your values are all known at compile time, you can do some template magic to make things happen during compilation, but that doesn't seem to be what you're trying to accomplish.


A possible (runtime) solution is to have implicit convertion operator to int that assert that your fraction is x/1.

class Fraction
{
   operator __int64() const
   {
      assert(den == 1);
      return num;
   }
}

It will allow you to pass Fraction to integers and check at runtime that it is correct. Not maybe what you exactly want, but this is the best you can have.


A possible solution would be an amalgamation of std::pair and boost::optional.

std::pair< boost::optional<Fraction>, boost::optional<int> > const operator+(Fraction const& lhs,Fraction const& rhs);
0

精彩评论

暂无评论...
验证码 换一张
取 消