c++ - Promotion of parameters during overloading -
i studying overloading , getting confused promotions. looked @ few articles in (implicit conversion sequence in function overloading) , sure more available, not find right article. referring http://www.dcs.bbk.ac.uk/~roger/cpp/week20.htm. looking @ c++ programming special edition stroustrup , came across following explanation.
finding right version call set of overloaded functions done looking best match between type of argument expression , parameters (formal arguments) of functions. approximate our notions of reasonable, series of criteria tried in order: 1 exact match [2] match using promotions; [3] match using standard conversions [4] match using user-defined conversions [5] match using 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 double promotion: print(double) }
i wrote below code. thinking if call function value of 1, func1(long) called because promotion takes place. error message "error: call of overloaded 'func1(int)' ambiguous". not calling function unsigned char type of variable.
also if pass call func1(3.4f), func1(double) called , promotion takes place per expectation. why 1 not promoted long int why float promoted double? integer promotions takeplace?
void func1(unsigned char speed) { cout<<"func1 unsigned char: speed =" << speed <<" rpm\n"; } void func1(long speed) { cout<<"func1 long int: speed =" << speed <<" rpm\n"; } void func1(double speed) { cout<<"func1 double: speed =" << speed <<" rpm\n"; } int main(void) { func1(1); func1(3.4f); return(0); }
the standard specifies:
[c++11: 4.13/1]:
("integer conversion rank")every integer type has integer conversion rank defined follows:
- [..]
- the rank of
long long int
shall greater the rank oflong int
, shall greater rank ofint
, shall greater rank ofshort int
, shall greater rank of signed char.- the rank of unsigned integer type shall equal rank of corresponding signed integer type.
- [..]
which calls ambiguity in example.
as func1(3.4f);
, it's promotion float double, , that's best match, since other 2 overloaded methods have long
, unsigned char
.
also check table:
where subclause specifies:
[conv.fpprom]:
(7.7 floating-point promotion )
- a prvalue of type
float
can converted prvalue of typedouble
. value unchanged.- this conversion called floating-point promotion.
Comments
Post a Comment