【问题标题】:Implicit cast from const string to bool [duplicate]从 const 字符串隐式转换为 bool [重复]
【发布时间】:2017-10-16 17:55:52
【问题描述】:

我有以下代码:

#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;
}

执行时我得到这个输出:

bool

我会期望输出:

string

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

【问题讨论】:

    标签: c++ g++ g++4.9


    【解决方案1】:

    您的编译器正在正确解释标准。是的,这是许多面试官提出的一个棘手的极端案例,因此他们看起来比实际更聪明。

    const char[2](文字 "1" 的正式类型)到 const char*bool 的路由是一个标准转换序列,因为它只使用内置类型。

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

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

    你可以在 C++11 中优雅地解决这个问题,方法是将你的重载放到bool,然后编写

    #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;
    }
    

    在它的位置。然后编译器将支持std::string 代替模板const char[N](因为这是重载决议的要求之一)。不错!

    【讨论】:

      【解决方案2】:

      "1" 是一个字符串文字,当用作函数参数时,它会衰减为const char* 类型的指针。由于函数foo 没有重载采用const char*,但是有一个从const char*bool 的标准转换,它回退到foo(bool)。请注意,当作为布尔参数时,指针值被解释为somePtr==nullptr ? false : true

      【讨论】:

        【解决方案3】:

        "1" 是一个字符串文字,即char 的数组,它先转换为指针,然后再转换为bool。请注意,此路径优先于隐式构造临时 std::string 对象。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2020-05-08
          • 1970-01-01
          • 2013-07-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-12
          • 2021-06-01
          相关资源
          最近更新 更多