为什么float参数的重载函数模板没有调用重载的普通float函数? [英] Why the overloaded function template for the float parameter does not call the overloaded ordinary float function?

查看:100
本文介绍了为什么float参数的重载函数模板没有调用重载的普通float函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码:

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



对于display(12.34),调用了模板函数,但是在int的情况下,调用了正常的重载显示函数,为什么呢?



For display(12.34), the template function is called but in case of int the normal overloaded display function is called, why?

推荐答案

12.34是double而不是a浮点数,并且双精度数不能以确保无损失的方式转换为浮点数.因此,将调用模板功能
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>

.

"c"是一个字符,可以自动转换为浮点数而不会丢失,因此调用了

is called.

''c'' is a char, which can be automatically converted to a float without loss, and therefore the

display( float(''c'') )

函数.


通常将值12.34视为double value.这就是为什么不调用显式函数的原因.因此,您可以将12.34强制转换为float或将显式函数用于double.
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.


这篇关于为什么float参数的重载函数模板没有调用重载的普通float函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆