为什么编译器在字符串上选择bool作为L“”的隐式类型转换? [英] Why does the compiler choose bool over string for implicit typecast of L""?

查看:133
本文介绍了为什么编译器在字符串上选择bool作为L“”的隐式类型转换?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近引入了一个方法的重载,应用程序开始失败。

Having recently introduced an overload of a method the application started to fail. Finally tracking it down, the new method is being called where I did not expect it to be.

我们有

setValue( const std::wstring& name, const std::wstring& value );

std::wstring avalue( func() );
setValue( L"string", avalue );
std::wstring bvalue( func2() ? L"true", L"false" );
setValue( L"bool", bvalue );
setValue( L"empty", L"" );

它被改变了,当一个bool值被存储时,我们使用相同的字符串string)

It was changed so that when a bool value is stored we use the same strings (internal data storage of strings)

setValue( const std::wstring& name, const std::wstring& value );
setValue( const std::wstring& name, const bool& value );

std::wstring avalue( func() );
setValue( L"string", avalue );
setValue( L"bool", func2() );
setValue( L"empty", L"" ); << --- this FAILS!?!

L的问题是它是隐式转换,以前它很高兴成为一个std :: wstring,但不是它更喜欢是一个bool。
MSVC编译器不会抱怨或者提醒警告,所以我担心即使我修复了setValue(Lempty,L);是

The problem with L"" is that it is implicitly casting and previously it was happy to be a std::wstring, but not it prefers to be a bool. The MSVC compiler does not complain, or raise warning, so I'm worried that even if I "fix" the setValue( L"empty", L"" ); to be

setValue( L"empty", std::wstring() );

别人可能会稍后再使用setValue(Lempty,L并且必须再次跟踪此问题。

somebody else may come later and simply use setValue( L"empty", L"" ); and have to track down this issue again.

我们认为对方法使用显式,但它不是一个有效的关键字这个用法。
有没有办法让编译器抱怨这个,否则防止问题?否则我想改变方法的名称,它需要一个bool,以确保它不能做错误的猜测。

We thought to use explicit on the method but it is not a valid keyword for this usage. Is there some way to get the compiler to complain about this, or otherwise prevent the issue? Otherwise I'm thinking to change the name of the method which takes a bool to ensure it can't make an incorrect guess.

推荐答案

p>首先,这个问题的原因:C ++ Standard 13.3.3.2 定义了转换序列的顺序。它说,用户定义的转换序列比标准转换序列差。在你的情况下会发生什么是字符串文字经历一个布尔转换(定义在 4.12 这是一个标准的转换)。它不使用用户定义的转换 std :: wstring ,如果它采取了其他重载,则需要。

First, the cause of this issue: C++ Standard 13.3.3.2 defines an order for conversion sequences. It says that a user defined conversion sequence is worse than a standard conversion sequence. What happens in your case is that the string literal undergoes a boolean-conversion (defined at 4.12. This is a standard conversion). It does not use the user defined conversion to std::wstring which would be needed if it took the other overload.

我建议简单地更改一个重载的名称或添加一个重载直接接受字符串文字(使用参数类型 wchar_t const * )。

I would recommend to simply change the name of one of the overloads or adding an overload that accepts the string literal directly (using parameter type wchar_t const*).

这篇关于为什么编译器在字符串上选择bool作为L“”的隐式类型转换?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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