在C ++中,当我将值传递给函数时,是否总是将其转换为适当的类型? [英] In C++, when I pass a value into a function, is it always converted to appropiate type?
问题描述
如果我有一个像void func(size_t x)
这样的函数并且调用了函数func(5)
,是否立即将5转换为size_t
类型?通常适用于所有类型吗?
If I have a function like void func(size_t x)
and I call the function func(5)
, is 5 immediately converted to size_t
type? Does this hold generally for all types?
我问是因为我发誓我见过人们在写代码的地方执行func(5.0)
(将5作为双精度值传递)或func(0UL)
(将0作为无符号long int传递值).这真的有必要吗?我们不能随便传入什么,C ++会将其视为我用来定义函数的类型吗?
I ask because I swear I've seen people write code where they do stuff like func(5.0)
(passing 5 as a double) or func(0UL)
(passing 0 as an unsigned long int). Is this really necessary? Can't we just pass in whatever we want, and C++ will treat it as the type that I used to define the function?
推荐答案
如果参数类型和传递给函数的类型之间存在隐式转换,则将转换参数.如果没有,例如尝试将std::list
传递给需要std::vector
的函数,那么它将不会,并且您会得到一个错误.
If there is an implicit conversion between the argument type and the type passed to the function then the argument will be converted. If there isn't one, like trying to pass a std::list
to a function that expects a std::vector
then it won't and you will get an error.
使用特定文字如func(5.0)
或func(5UL)
的一个原因是func
是模板函数,还是被重载.如果func
是模板或过载(对于适当的类型),则func(5.0)
,func(5UL)
和func(5)
将生成/调用3个不同的函数.一个用于double
,一个用于unsigned long
,一个用于int
.这可能是有意义的,因为可能会有专门化/超负荷对这些类型进行不同的处理.
One reason to use a specific literal, like func(5.0)
or func(5UL)
is if func
is a template function, or is overloaded. If func
is a template or is overloaded (for the appropriate types) then func(5.0)
, func(5UL)
and func(5)
would generate/call 3 different functions. One for a double
, one for a unsigned long
and one for an int
. This could be meaningful as there could be specializations/overloads handling these types differently.
您还会遇到类似std::accumulate
的情况,其第三个参数累加器具有自己的模板类型.假设您想对std::vector<double>
中的所有元素求和.如果您使用
You also run into cases like std::accumulate
whose third parameter, the accumulator, has its own template type. Lets say you want to sum all of the elements in a std::vector<double>
. If you use
std::accumulate(vector.begin(), vector.end(), 0)
那么您得到的结果将不同于
then you would get a different result than
std::accumulate(vector.begin(), vector.end(), 0.0)
因为第一次调用使用int
存储每次将截断的总和,而后者使用double
则您将获得预期的结果.
because the first call uses an int
to store the sum which will truncate each time, while the latter uses a double
and you will get the expected result.
这篇关于在C ++中,当我将值传递给函数时,是否总是将其转换为适当的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!