codosopher
codosopher

Reputation: 171

Why can't `std::min` be used between `int` and `long long int`

So I just want to know that why I can't pass values with different datatypes in min and max function?

int a=7;
long long int b=5;
long long int c=min(a,b);
cout<<c;

My doubt arises because what I know for sure that compiler can implicitly type cast from smaller datatype(int) to larger datatype(long long int) so why not compiler couldn't type cast here!

Upvotes: 6

Views: 4979

Answers (2)

HolyBlackCat
HolyBlackCat

Reputation: 96336

This comes down to how std::min and std::max were designed.

They could've had two different types for the two parameters, and use something like std::common_type to figure out a good result type. But instead they have the same type for both parameters, so the two arguments you pass must also have the same type.

compiler can implicitly type cast from smaller datatype(int) to larger datatype(long long int)

Yeah, but it also can implicitly convert back from long long to int. ("Cast" isn't the right word, it means an explicit conversion.)

The rule is that when a function parameter participates in template argument deduction, no implicit conversions are allowed for the argument passed to that parameter. Deduction rules are already compilcated, allowing some implicit conversions (i.e. to wider arithmetic types) would make them even more complex.

Upvotes: 5

Yug soni
Yug soni

Reputation: 8

Because there is loss of precision error comes when you do this they are made for the int datatypes so you cannot pass long or something like float. You have to implicit cast them.

Upvotes: -3

Related Questions