gcc深/双/嵌套铸造

que*_*en3 0 c++ gcc visual-c++

首先是代码

#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;
}
Run Code Online (Sandbox Code Playgroud)

这里的问题是container()可以转换为_bstr_t然后wchar_t*,但是,gcc没有.

可以使用手动转换解决问题:

wchar_t *str = (_bstr_t)container();
Run Code Online (Sandbox Code Playgroud)

但我需要的是避免手动播放,我希望gcc能够自动解决这个问题.

为什么我需要这个是因为返回的容器类型对象将在调用中使用

void Func(wchar_t* str);
Func(myObject->Container);
Run Code Online (Sandbox Code Playgroud)

我不想做手工铸造的地方.

我验证了Visual Studio,它似乎也不支持这种情况.太糟糕了,但如果有人可以提供解决方法,我会很高兴,即使是针对这个特定情况.

更新:对于那些在容器上建议运算符wchar_t*的人来说,这首先是问题所在.在Func()有机会接受指针之前,这将在销毁时泄漏或崩溃.

Cat*_*lus 6

进行隐式转换时,最多只能进行一次用户定义的转换.在这个问题上,MSVC行为不符合标准.

C++ 11(12.3转换):

最多一个用户定义的转换(构造函数或转换函数)隐式应用于单个值.

对于隐式转换工作,container必须直接转换为wchar_t*.