错误的功能被选中 [英] wrong function being picked
问题描述
我试图清除一些使用 char *
和 std :: string
的代码,
I was trying to clean up some code that uses char*
with std::string
and ran into a problem that is illustrated by the following code.
void Foo( int xIn , const std::string & fooIn )
{
std::cout << "string argument version called \n";
}
void Foo( int xIn , bool flagIn = true )
{
std::cout << "bool argument version called \n";
}
int main()
{
int x = 1;
Foo( x , "testing" );
return 0;
}
当我运行程序时,我获得 bool参数版本<强>。是 char *
到 bool
转换优先于 char *
到 const std :: string&
或者是Visual Studio 2008在我身上玩耍?
When I run the program I get bool argument version called. Is a char*
to bool
conversion preferred over char*
to const std::string&
or is Visual Studio 2008 playing tricks on me ?
推荐答案
令人惊讶的是,这种行为是,编译器兼容: char *
到 bool
转换为 std :: string
。
阅读更多这里。
在C ++标准中。它们非常复杂,但以下段落至关重要:
The exact rules are spelled out in the C++ standard. They're surprisingly complicated, but the following paragraph is crucial here:
C ++ 11 13.3.3.2排序隐式转换序列[over.ics.rank]
2
当比较隐式转换序列的基本形式(如13.3中定义的
) 3.1) - 标准转换序列(13.3.3.1.1)是
a比用户定义的转换序列更好的转换序列
或省略号转换序列
2 When comparing the basic forms of implicit conversion sequences (as defined in 13.3.3.1) — a standard conversion sequence (13.3.3.1.1) is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence
char *
-to - bool
需要标准转换序列 char *
-to - string
需要用户定义的转换序列。因此,前者是首选。
char*
-to-bool
requires a "standard conversion sequence" whereas char*
-to-string
requires a "user-defined conversion sequence". Therefore, the former is preferred.
这篇关于错误的功能被选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!