Click here to Skip to main content
15,890,825 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Here is my code:

#include<iostream.h>
#include<conio.h>

template <class t="">
 void display(T x)
         {
              cout<<"Template display :"<<x<<"\n";
         }
         
         
          void display(float x)                                  
         {
              cout<<"Explicit display: float "<<x<<"\n";
         }
       
         
         
         int main()
         {
            
             
             display(12.34);
             display('c');
             getch();
             return 0;
         }


For display(12.34), the template function is called but in case of int the normal overloaded display function is called, why?
Posted
Updated 17-Aug-11 0:26am
v4

12.34 is a double, not a float, and doubles can't be converted to floats in a way that is guaranteed to be loss-free. Therefore, the template function
display<double>(12.34)</double>
is called.

'c' is a char, which can be automatically converted to a float without loss, and therefore the
display( float('c') )
function is called.
 
Share this answer
 
Normally value 12.34 will be considered as double value.That is why your explicit function is not called.so you can cast the 12.34 to float or use explicit function for double.
 
Share this answer
 
Comments
Philippe Mori 17-Aug-11 23:41pm    
You should do an overload... Otherwise, everytime, the cast if forgotten, the wrong function would be called. And, by the way, we should avoid cast whenever possible.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900