简体   繁体   中英

function static binding in C++

I am asking about the static binding of the function in C++. What's the data type conversion rules for the function binding.

Suppose we have

void func(int x);
void func(long x);
void func(float x);
void func(double x);
void func(char x);

and I have one function in main

func(1)

I know the function func(int x) will be called. I am curious about the rules of that.

Is it always the best match?

Does the order of declaration matter?

In any case the data type conversion will be applied?

What's the concern when the rules are designed?

Is it always the best match?

Yes: 1 is an int . If an appropriate overload exists, it will be taken since this minimizes the number of necessary implicit conversions (none).

Does the order of declaration matter?

No. However, it matters whether a function has been declared before the call is made. If the function is declared after the call, it will not be taken into consideration for overload resolution.

In any case the data type conversion will be applied?

There's no conversion here because int is an exact match. Conversions only come into play when there's no exact match available.

What's the concern when the rules are designed?

Well, it's the only rule that makes sense, isn't it?

The constant 1 has type int so the best match is void func(int) . The order of declaration does not affect. Type conversion will come into play when there is a best match (no ambiguity) but the match and the argument don't have the same type as the argument.

In C++ it is always best match. Order of declaration does not matter. And yes constant has type conversion. For example if You write another overload:

void func(std::string const& x);

Then call:

func("Hi there");

Then compiler will use func(std::string const& x) overload as std::string contain constructor taking char const * and use that as one of type conversion rules. Then temporary std::string will be constructed and passed to func.

有类型常量,例如, unsigned 1 1u以及long 1 1l ,以及带有double( 1.0 )和float( 1.0f )的常量。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM