0

I've been experimenting with decltype, trying to figure out the potential benefits of it. I ran this very simple function:

template<class T, class U>
auto MyFunc(T t, U u) -> decltype(t < u ? t : u)
{
  return t < u ? t : u;
}

when calling the function:

auto d = MyFunc(3,3.5);

std::cout << d<<'\n';
std::cout<<"type: "<<typeid(d).name();

I get the following result:

3
type: d

My question is why the returned type is d (decimal) not i (integer)? Thanks!

SAR
  • 148
  • 1
  • 8

2 Answers2

0

You can't return two different types depending on the values of the input. Therefore it choses the widest compatible type, here double

Vivick
  • 2,051
  • 2
  • 6
  • 19
0

The compiler does not dynamically look up the types in this context. It needs to create the template instance so it chooses the most suitable type, which is double because if it would choose int, there might be a data loss conversion from double to int if it would be the case.