我试图清理使用一些代码char*与std::string跑进由下面的代码所示的问题.
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;
}
Run Code Online (Sandbox Code Playgroud)
当我运行程序时,我得到bool参数版本调用.是一个char*以bool转换优于char*到const std::string&或Visual Studio 2008中捉弄我吗?
NPE*_*NPE 27
令人惊讶,因为这种行为是,编译器是兼容的:char*到bool转换优于转化成std::string.
在这里阅读更多.
确切的规则在C++标准中有详细说明.它们非常复杂,但以下段落至关重要:
C++ 11 13.3.3.2对隐式转换序列进行排序[over.ics.rank]
2比较隐式转换序列的基本形式(如13.3.3.1中所定义) - 标准转换序列(13.3.3.1.1)是比用户定义的转换序列或省略号转换序列更好的转换序列
char*-到- bool需要一个"标准的转换序列",而char*-到- string需要一个"用户定义的转换序列".因此,前者是优选的.
它们都是潜在的匹配,但bool编译器首选版本,因为为了匹配string版本,需要用户提供的(或者,在本例中为库提供的)转换函数.
如果你真的想这样做,提供一个过载const char*可以让你到那里:
void Foo( int xIn, const char* in)
{
return Foo( xIn, string(in) );
}
Run Code Online (Sandbox Code Playgroud)
我猜想通过这样做,编译器很可能会对它进行相当多的优化.