由于最近引入了一个方法的重载,应用程序开始失败。最后,新方法被调用了,这是我没想到的地方。
我们有过
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"" );对其进行了更改,以便在存储布尔值时使用相同的字符串(字符串的内部数据存储)
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"“);,并且必须再次跟踪此问题。
我们想在方法上使用explicit,但它不是用于此用法的有效关键字。有没有办法让编译器抱怨这个问题,或者以其他方式防止这个问题?否则,我正在考虑更改方法的名称,该方法需要一个布尔值,以确保它不会做出错误的猜测。
发布于 2008-11-25 03:03:34
L"“是指向宽字符串的指针。编译器认为到bool的转换优先于到std::wstring的转换。
要解决此问题,请引入新的setValue:
void setValue(std::wstring const& name, const wchar_t * value);发布于 2008-11-25 03:19:28
由于bool是一种内置类型,因此首选从wchar_t转换为bool。我要说的是,最简单的解决方案是添加一个重载,它接受一个wchar_t数组并在其中显式转换:
setValue( const std::wstring& name, const wchar_t s[] )
{
setValue(name, wstring(s));
}发布于 2008-11-25 02:48:27
为了简化一点,下面的代码
#include <iostream>
using namespace std;
void f(const string &s)
{ cout << "string version called" << endl; }
void f(const bool &b)
{ cout << "bool version called" << endl; }
int main()
{ f("Hello World"); }打印"bool version called“。您确定您的代码只有在出现空字符串时才失败吗?
https://stackoverflow.com/questions/316181
复制相似问题