Andreas DM
Andreas DM

Reputation: 10998

Deducing template return type based on operator?: result

Consider this code:

template <typename T1, typename T2>
auto max(T1 t1, T2 t2) -> decltype(true?t1:t2)
{
  return t2 < t1 ? t1 : t2;
}

When calling this function with ::max(5, 7.2) I'm expecting the returned type to be int as decltype(t1) is in this case int.

Why is the deduced return type double in the above code when using operator?: inside the decltype?

If I do -> decltype(t1) I get the expected return type int.

Upvotes: 1

Views: 58

Answers (1)

songyuanyao
songyuanyao

Reputation: 172894

Note that the result type of conditional operator is determined at compile-time. It won't return different types based on the condition but would return the common type of the operands as the result.

6.2) If both E2 and E3 have arithmetic or enumeration type: the usual arithmetic conversions are applied to bring them to common type, and that type is the result.

And for this case, i.e. one operand is int and another is double, the result type will be double.

  • Otherwise, if either operand is double, the other operand is converted to double

BTW: You can use std::common_type (since C++11) to get the common type.

Upvotes: 5

Related Questions