从const字符串到bool的隐式转换

Dav*_*ius 5 c++ g++ g++4.9

我有以下代码:

#include <iostream>
#include <string>

void foo(bool a)
{
        std::cout << "bool" << std::endl;
}

void foo(long long int a)
{
        std::cout << "long long int" << std::endl;
}

void foo(const std::string& a)
{
        std::cout << "string" << std::endl;
}

int main(int argc, char* args[])
{
        foo("1");
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

执行时我得到这个输出:

bool
Run Code Online (Sandbox Code Playgroud)

我原以为输出:

string
Run Code Online (Sandbox Code Playgroud)

为什么g ++ 4.9隐式将此字符串转换为bool?

Bat*_*eba 7

您的编译器正确解释标准.是的,这是一个棘手的角落案例,很多采访者都会这么认为,所以他们看起来比实际更聪明.

路线const char[2](正规型字面的"1"),以const char*bool是一个标准的转换序列,因为它使用专用的内置类型.

您的编译器必须支持用户定义的转换序列,即.std::string来自的构造函数const char*.

过载的存在void foo(long long int a)是一个红鲱鱼.

你可以通过放弃重载bool和编写来优雅地在C++ 11中解决这个问题

#include <type_traits>
template <
    typename Y,
    typename T = std::enable_if_t<std::is_same<Y, bool>{}>
>
void foo(Y)
{
  std::cout << "bool" << std::endl;
}
Run Code Online (Sandbox Code Playgroud)

在它的位置.然后,编译器会偏向std::stringconst char[N]在模板(因为这是超负荷决议的要求之一).太好了!