First is the code
#include <stdio.h>
typedef wchar_t* BSTR;
wchar_t hello[] = L"Hello";
class _bstr_t {
public:
operator const wchar_t*() const throw() { return hello; }
operator wchar_t*() const throw() { return hello; }
};
class container {
public:
operator _bstr_t() { return _bstr_t(); }
};
int main()
{
// This gives error (with gcc 4.5.2 at least):
// test.cpp:20:27: error: cannot convert "container" to "wchar_t*" in initialization
wchar_t *str = container();
printf("%S\n", str);
return 0;
}
The problem here is that container() can be casted to _bstr_t and then to wchar_t*, but, gcc does not.
The problem can be solved using manual cast:
wchar_t *str = (_bstr_t)container();
But what I need is to avoid manual cast, I would like gcc to figure this out automatically.
Why I need this is because the returned container type objects will be used in calls like
void Func(wchar_t* str);
Func(myObject->Container);
where I don’t want to do manual casting.
I verified Visual Studio and it does not seem to support such scenario, too. Too bad, but I would be glad if someone can provide a workaround, even if for this specific case.
UPDATE: for those who suggests operator wchar_t* on the container, that was the problem in first place. This will either leak or crash when destroyed before Func() has a chance to accept the pointer.
When doing implicit conversions, there’s at most one user-defined conversion that can happen. MSVC behaviour is not standard compliant in this matter.
C++11 (12.3 Conversions):
For the implicit conversion to work,
containerhas to convert directly towchar_t*.