Sirish Kumar Bethala
Sirish Kumar Bethala

Reputation: 9279

Why does the compiler not resolve this call to a template function?

In below program why does the compiler generate an error for the call to the printMax template function and not the call to the printMaxInts function?

#include <iostream>

template<class A>
void printMax(A a,A b)
{
   A c = a>b?a:b;

   std::cout<<c;
}

void printMaxInts(int a ,int b)
{
   int c = a>b?a:b;

   std::cout<<c;

}

int main()
{
   printMax(1,14.45);

   printMaxInts(1,24);
}

Upvotes: 1

Views: 169

Answers (2)

pkh
pkh

Reputation: 3749

The following code builds on James's answer. You'll notice that I've taken out the conditional expression: I've done this because the result clauses to that expression must have the same type, which imposes an additional restriction on A and B.

The only requirements on A and B in this version of the code is that there's an operator<() that related them (or one can be converted to the other), and that the requisite operator<<() functions exist.

template<typename A, typename B>
void printMax(A a, B b)
{    
    if (a < b) 
    {
        cout << b;
    }
    else 
    {
        cout << a;
    }
}

Upvotes: 1

James McNellis
James McNellis

Reputation: 355357

In order for the compiler to deduce the template parameter A from the arguments passed to the function template, both arguments, a and b must have the same type.

Your arguments are of type int and double, and so the compiler can't deduce what type it should actually use for A. Should A be int or should it be double?

You can fix this by making both arguments have the same type:

printMax(1.0, 14.45);

or by explicitly specifying the template parameter:

printMax<double>(1, 14.45);

The reason that the call to the non-template function can be called is that the compiler does not need to deduce the type of the parameters: it knows the type of the parameters because you said what they were in the function declaration:

void printMaxInts(int a, int b)

Both a and b are of type int. When you pass a double as an argument to this function, the double -> int standard conversion is performed on the argument and the function is called with the resulting int.

Upvotes: 6

Related Questions