开发者

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 rule开发者_运维知识库s 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.


There are typed constants, for example 1u for an unsigned 1 as well as 1l for a long 1 and the same with double (1.0) and float (1.0f).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜