超载时参数的提升

问题描述:

我正在研究超载问题,而且我完全被升级困惑。我查看了SO(implicit conversion sequence in function overloading)中的一些文章,我确定有更多文章可用,但无法找到正确的文章。我也是指http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm。 我在看Stroustrup的C++编程特别版,并且遇到了下面的解释。超载时参数的提升

Finding the right version to call from a set of overloaded functions is done by looking for a best match between the type of the argument expression and the parameters (formal arguments) of the functions. To approximate our notions of what is reasonable, a series of criteria are tried in order: 1 Exact match [2] Match using promotions; [3] Match using standard conversions [4] Match using user-defined conversions [5] Match using the ellipsis ......

void print(int); 
void print(double); 
void print(long); 
void print(char); 
void h(char c, int i, short s, float f) 
{ 
    print(s); // integral promotion: invoke print(int) 
    print(f); // float to double promotion: print(double) 
} 

我写了下面的代码。我在想,如果我调用值为1的函数,func1(long)将被调用,因为促销发生。但我得到错误消息“错误:重载调用'func1(int)'不明确”。它不用甚至无符号的char类型的变量调用该函数。

此外,如果我通过调用func1(3.4f),func1(double)被调用,促销发生在我的期望。为什么1不被提升为long int,但为什么float被提升为double?什么样的整数促销活动?

void func1(unsigned char speed) 
    { 
     cout<<"Func1 with unsigned char: speed =" << speed <<" RPM\n"; 
    } 

    void func1(long speed) 
    { 
     cout<<"Func1 with long Int: speed =" << speed <<" RPM\n"; 
    } 

    void func1(double speed) 
    { 
     cout<<"Func1 with double: speed =" << speed <<" RPM\n"; 
    } 

    int main(void) 
    { 
     func1(1); 
     func1(3.4f); 
     return(0); 
    } 

该标准规定:

[C++11: 4.13/1]: ("Integer conversion rank")

Every integer type has an integer conversion rank defined as follows:

  • [..]
  • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int , which shall be greater than the rank of signed char.
  • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type.
  • [..]

这就要求在你的榜样歧义。

至于func1(3.4f);,它只是一个从浮子双重推动下,这是最好的比赛,因为其他两个重载方法有longunsigned char

还要检查这个table

enter image description here

其中一节规定:

[conv.fpprom]: (7.7 Floating-point promotion)

  • A prvalue of type float can be converted to a prvalue of type double . The value is unchanged.
  • This conversion is called floating-point promotion.
+0

感谢@StoryTeller!那么是的,但不是一个更好的比赛? – gsamaras

+0

@StoryTeller感谢您帮助我改进我的答案。我更新了,现在看起来如何? – gsamaras

+0

这意味着在整数类型的情况下,不会发生促销,我们需要为每个整数类型重载函数?另外,如果我有func1(char)和func1(unsigned char),我怎么能看到func1(unsigned char)函数被调用?可能我需要传递一个ASCII值超过127的字符,这在键盘上可能是不可能的! – Rajesh