当使用winapi HWND并返回wstring时,我有一个函数。
std::wstring utility::winapi::window_class(HWND hwnd) {
int title_length = 20;
std::wstring class_name;
class_name.resize(title_length, '\0');
GetClassName(hwnd, const_cast<LPWSTR>(class_name.c_str()), title_length);
class_name.erase(std::remove_if(class_name.begin(), class_name.end(), [](const char &x){return x == '\0';}), class_name.end());
return class_name;
}
我收到以下错误:C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.27.29110\include\xmemory(2040): error C2220: the following warning is treated as an error
..\..\libs\utility\src\winapi.cpp(44): note: see reference to function template instantiation '_FwdIt std::remove_if<std::_String_iterator<std::_String_val<std::_Simple_types<_Elem>>>,utility::winapi::window_class::<lambda_1>>(_FwdIt,const _FwdIt,_Pr)' being compiled
with
[
_FwdIt=std::_String_iterator<std::_String_val<std::_Simple_types<wchar_t>>>,
_Elem=wchar_t,
_Pr=utility::winapi::window_class::<lambda_1>
]
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.27.29110\include\xmemory(2040): warning C4244: 'argument': conversion from 'wchar_t' to 'const char', possible loss of data
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.27.29110\include\xutility(5667): warning C4244: 'argument': conversion from '_Elem' to 'const char', possible loss of data
with
[
_Elem=wchar_t
]
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.27.29110\include\xmemory(2036): note: see reference to function template instantiation '_InIt std::find_if<wchar_t*,_Fn>(_InIt,const _InIt,_Pr)' being compiled
with
[
_InIt=wchar_t *,
_Fn=utility::winapi::window_class::<lambda_1>,
_Pr=utility::winapi::window_class::<lambda_1>
]
..\..\libs\utility\src\winapi.cpp(44): note: see reference to function template instantiation '_FwdIt std::remove_if<std::_String_iterator<std::_String_val<std::_Simple_types<_Elem>>>,utility::winapi::window_class::<lambda_1>>(_FwdIt,const _FwdIt,_Pr)' being compiled
with
[
_FwdIt=std::_String_iterator<std::_String_val<std::_Simple_types<wchar_t>>>,
_Elem=wchar_t,
_Pr=utility::winapi::window_class::<lambda_1>
]
ninja: build stopped: subcommand failed.
此错误是什么意思?UPD:已更新,并显示完整错误。
最佳答案
class_name
声明为std::wstring
。这是一串wchar_t
值,但是您的lambda参数为const char &
类型,它的范围更窄。警告告诉您该值可能会被截断。在应注意的情况下,这可能导致测试x == '\0'
评估为true。这是编译器试图告诉您的:
warning C4244: 'argument': conversion from 'wchar_t' to 'const char', possible loss of data
附带说明,没有理由通过引用接受数字参数。在这种情况下,很可能会导致组装相同,因为几乎可以肯定会内联lambda,但不使用引用会更干净。要解决警告,请更改lambda以接受
wchar_t
:[](wchar_t x){return x == '\0';})
从C++ 14开始,您还可以使用auto
作为参数的类型:[](auto x){return x == '\0';})
关于c++ - 在std::wstring上使用std::remove_if的警告(MSVC C++ 20),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63644227/