gcc深/双/嵌套铸造
gcc deep/double/nested casting
首先是代码
#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("%Sn", str);
return 0;
}
这里的问题是container()
可以被广播到_bstr_t
,然后再广播到wchar_t*
,但是gcc不能。
该问题可以使用手动铸造解决:
wchar_t *str = (_bstr_t)container();
但我需要的是避免手动强制转换,我希望gcc能自动解决这个问题。
我之所以需要这个是因为返回的容器类型对象将用于之类的调用
void Func(wchar_t* str);
Func(myObject->Container);
我不想做手动选角。
我验证了Visual Studio,它似乎也不支持这样的场景。太糟糕了,但如果有人能提供一个变通办法,我会很高兴,即使是在这个特定的情况下。
更新:对于那些建议在容器上使用运算符wchar_t*的人,认为首先是问题所在。当在Func()有机会接受指针之前被销毁时,它将泄漏或崩溃。
在进行隐式转换时,最多可以进行一次用户定义的转换。MSVC的行为在这件事上不符合标准。
C++11(12.3转换):
最多一个用户定义的转换(构造函数或转换函数)隐式应用于单个值。
为了使隐式转换工作,container
必须直接转换为wchar_t*
。
它不起作用,因为类容器没有operator wchar_t*()
。唯一的解决方案是将其添加到容器类:
#include <iostream>
typedef wchar_t* BSTR;
wchar_t hello[] = L"Hello";
class container {
public:
operator const wchar_t*() const throw() { return hello; }
operator wchar_t*() const throw() { return hello; }
};
int main()
{
// This gives error (with gcc 4.5.2 at least):
// test.cpp:20:27: ошибка: cannot convert «container» to «wchar_t*» in initialization
wchar_t *str = container();
std::wcout<<str<<std::endl;
}
您没有从wchar_t *
到container
的转换器,这就是为什么您会得到错误
class container {
public:
operator wchar_t*() { return _bstr_t(); }
};
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 修改嵌套 lambda 中捕获的参数:gcc 与 clang?
- 带有可变参数的嵌套宏在GCC中编译,但在MSVC中不编译
- 通过指向成员的指针对嵌套访问进行编译时评估期间出现 GCC 错误
- 为什么 GCC 允许从私有嵌套类继承
- 为什么 GCC 不允许在你是朋友时从私有嵌套类继承
- gcc segfault在编译嵌套参数包代码上
- 在类嵌套静态常量成员变量初始化 Clang vs GCC 哪个编译器是正确的
- 为什么具有多个嵌套循环的代码可以在 GCC 上立即完成,但在 VS 上需要很长时间
- 当在嵌套的lambda中使用“decltype”时,GCC的分离错误
- 嵌套的可变模板:gcc或clang中的错误
- gcc深/双/嵌套铸造
- 两层嵌套的c++类适用于GCC,但不适用于Clang
- c++ (gcc)嵌套模板问题
- 预期的嵌套名称说明符- gcc
- 奇怪的嵌套类部分特化结果在 gcc 和 clung 上
- GCC 错误:嵌套名称说明符中使用的类型"claculator"不完整
- 使用GCC优化C/ c++循环中的嵌套if语句
- 嵌套模板gcc编译器4.1.2错误