从const字符串隐式强制转换为bool [英] Implicit cast from const string to bool

查看:205
本文介绍了从const字符串隐式强制转换为bool的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

  #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);
返回0;
}

执行时,我得到这个输出:

  bool 

输出:

 字符串

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

您的编译器正在正确地解释标准。是的,这是一个棘手的角落案例,许多采访者要求他们看起来比他们真正聪明。


$ b 路线 const char [2] (文字1)到 const char * 到<$的正式类型c $ c> bool 是一个标准转换序列,因为它仅使用内置类型。



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



重载的存在 void foo(long long int a)是一条红色鲱鱼。



你可以在C ++ 11中通过将你的重载放到 bool ,并写入

  #include< type_traits> 
模板<
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] (因为这是一个的重载分辨率要求)。很好!


I have the following code:

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

When executing I get this output:

bool

I would have expected as output:

string

Why does g++ 4.9 implicitly cast this string to bool?

解决方案

Your compiler is interpreting the standard correctly. Yes, this is a tricky corner case that many interviewers ask so they appear smarter than they really are.

The route const char[2] (the formal type of the literal "1") to const char* to bool is a standard conversion sequence, since it uses exclusively built-in types.

Your compiler must favour that to a user-defined conversion sequence, viz. the std::string constructor from a const char*.

The presence of the overload void foo(long long int a) is a red herring.

You can rather elegantly work around this in C++11 by dropping your overload to bool, and writing

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

in its place. The compiler will then favour the std::string for const char[N] over the template (as that is one of the requirements of overload resolution). Nice!

这篇关于从const字符串隐式强制转换为bool的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆