选择了错误的功能

par*_*mar 26 c++ visual-c++

我试图清理使用一些代码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需要一个"用户定义的转换序列".因此,前者是优选的.

  • @Vlad ..什么是**安全bool**替代品? (4认同)
  • @Vlad:当您希望用户定义的类型提供到bool的转换时,[safe bool idiom](http://en.wikibooks.org/wiki/More_C%2B%2B_Idioms/Safe_bool)非常有用.这里,转换是在两种原始类型之间进行的,因此安全bool习语不适用. (2认同)

Joh*_*ing 9

它们都是潜在的匹配,但bool编译器首选版本,因为为了匹配string版本,需要用户提供的(或者,在本例中为库提供的)转换函数.

如果你真的想这样做,提供一个过载const char*可以让你到那里:

void Foo( int xIn, const char* in)
{
    return Foo( xIn, string(in) );
}
Run Code Online (Sandbox Code Playgroud)

我猜想通过这样做,编译器很可能会对它进行相当多的优化.