- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
最近引入了一个方法的重载,应用程序开始失败。终于追踪到,新方法在我没想到的地方被调用了。
我们有
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 值时我们使用相同的字符串(字符串的内部数据存储)
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( L"empty", L"");成为
setValue( L"empty", std::wstring() );
其他人可能稍后会来并简单地使用 setValue( L"empty", L"");并且不得不再次追踪这个问题。
我们想在方法上使用显式,但它不是这种用法的有效关键字。有什么方法可以让编译器提示这个问题,或者以其他方式阻止这个问题吗?否则我正在考虑更改采用 bool 的方法的名称,以确保它不会做出错误的猜测。
最佳答案
首先,这个问题的起因:C++ Standard [over.ics.rank]/2.1
1 定义转换序列的顺序。它说用户定义的转换序列比标准转换序列差。在你的情况下发生的是字符串文字经历了 bool 转换(在 4.12
定义。这是一个标准转换)。它不使用用户定义的到 std::wstring
的转换,如果它采用其他重载,则需要这种转换。
我建议简单地更改其中一个重载的名称或添加一个直接接受字符串文字的重载(使用参数类型 wchar_t const*
)。
1)
When comparing the basic forms of implicit conversion sequences (as defined in
[over.best.ics]
)(2.1) a standard conversion sequence is a better conversion sequence than a user-defined conversion sequence or an ellipsis conversion sequence, and
(2.2) a user-defined conversion sequence is a better conversion sequence than an ellipsis conversion sequence.
关于c++ - 为什么编译器选择 bool 而不是 string 来进行 L""的隐式类型转换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39251626/
我是一名优秀的程序员,十分优秀!