开发者

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

开发者 https://www.devze.com 2023-01-14 01:37 出处:网络
In below program why does the compiler generate an error for the call to the printMax template fun开发者_运维知识库ction and not the call to the printMaxInts function?

In below program why does the compiler generate an error for the call to the printMax template fun开发者_运维知识库ction 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);
}


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.


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;
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消