porting std::wstring from visual studio to mingw gcc

孤街醉人 提交于 2019-12-14 02:04:26

问题


I am in the process of porting some code from Visual studio to mingw gcc. I came across this statement

if ( mnode.GetTag() == _T( "val" ) )    
        return  true;

this is the definition of GetTag() method

const std::wstring &GetTag() const;

I am getting the error

error: no matching function for call to 'std::basic_string<wchar_t>::basic_string(const char [6])'|

Now after reading this I am still not sure how to resolve this issue. Any suggestions on why this error is being shown up ? is it because of wstring ?


回答1:


It looks like your problem is that the _UNICODE preprocessor macro is not defined. MSDN explains how this affects string literal enclosed in the _T() macro.

 pWnd->SetWindowText( _T("Hello") );

With _UNICODE defined, _T translates the literal string to the L-prefixed form; otherwise, _T translates the string without the L prefix.

Adding an L prefix to a string literal indicates it is a wide string literal, and std::wstring (or std::basic_string<wchar_t>) defines an operator== overload that takes a wchar_t const * argument, thus allowing your code to compile.

Be aware that there's also a UNICODE macro that's relevant if you're going to be calling functions in the Windows API. Raymond Chen explains the madness quite well in this post.

So, one way to fix your problem is to add both _UNICODE and UNICODE preprocessor symbols to the gcc command line.

But don't do this! This is my opinion on the matter — instead of depending on obscure macros just prefix the string literal with L manually. Especially in this case, since you say that GetTag() always returns a wstring const&, I'd say using the _T() macro for that string literal is a bug.

Even otherwise, when calling Windows API functions, just call the wide character version explicitly. For instance, replace calls to GetWindowText with GetWindowTextW.



来源:https://stackoverflow.com/questions/28639114/porting-stdwstring-from-visual-studio-to-mingw-gcc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!