Sabien
Sabien

Reputation: 219

Which function would be called if a function template exists that could match another overloaded function?

In C++, say you have two function definitions:

template <typename T>
T square (T num);

And

double square(double num);

and you have a function call like:

square(1.5);

which function would be called? Which does the compiler choose?

Upvotes: 1

Views: 78

Answers (3)

Brian Bi
Brian Bi

Reputation: 119239

The argument 1.5 is of type double so it exactly matches both the template and non-template. In such a case the non-template function will be preferred according to [over.best.match] in the standard:

... F1 is defined to be a better function than ... F2 if ... F1 is not a function template specialization and F2 is a function template specialization ...

If you called square with an int or float argument, the template would again give an exact match but you'd need a conversion or promotion for the non-template. The template would be selected since it's a better match.

Upvotes: 4

ravi
ravi

Reputation: 10733

In this case C++ always prefers non-template version of function as it could easily promote float to double.

Had you used this:-

float p = 2.2;
square(p);

compiler would have chosen template version in its venture for perfect match.

Upvotes: 2

Ali Kazmi
Ali Kazmi

Reputation: 1458

Since call syntax matches the non-template function, so it will be called

Upvotes: 1

Related Questions