Is there a way to write a BSTR literal?

China☆狼群 提交于 2019-12-05 18:08:58

To follow up on @MSalters's answer, a custom user-defined literal could look something like this:

CComBSTR operator "" _bstr (const char* str, std::size_t len)
{
    return CComBSTR(len, str);
}

Then you can do this (as CComBSTR has a BSTR conversion operator defined):

iFoo->function( "HELLO"_bstr );

You can even overload the operator for multiple input string literal types:

CComBSTR operator "" _bstr (const wchar_t* str, std::size_t len)
{
    return CComBSTR(len, str);
}

CComBSTR operator "" _bstr (const char16_t* str, std::size_t len)
{
    return CComBSTR(len, (wchar_t*)str);
}

iFoo->function( L"HELLO"_bstr ); // calls wchar_t* version with UTF-16 encoded data

iFoo->function( u"HELLO"_bstr ); // calls char16_t* version with UTF-16 encoded data

iFoo->function( u8"HELLO"_bstr ); // calls char* version with UTF-8 encoded data...

Note the last case. Since the operator will not know whether it is being passed ANSI or UTF-8 data, and CComBSTR assumes ANSI when passed char* data, you should use a different literal suffix to differentiate so you can convert the UTF-8 correctly, eg:

CComBSTR operator "" _utf8bstr (const char* str, std::size_t len)
{
    std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> conv;
    std::wstring wstr = conv.from_bytes(std::string(str, len));
    return CComBSTR(wstr.length(), wstr.c_str());
}

iFoo->function( u8"HELLO"_utf8bstr );

User defined literals would be the way to go:

"HELLO"_bstr calls template<char...> BSTR operator "" _bstr ( const char*, std::size_t) which can then call SysAllocString()

New in VS14.

[edit]

Based on the comments, it might be better to return a _bstr_t or other class which takes ownership of the SysAllocString() result and implicitly converts to BSTR. This temporary will be destroyed at the end of the full expression, and therefore after iFoo->function( "HELLO"_bstr ); returns.

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