Can offsetof
与通过获得的类型一起使用decltype
?这两种情况中的任何一种都有效 C++11 吗?
struct S {
int i;
int j { offsetof(decltype(*this), i) }; // case 1
S() : i(offsetof(decltype(*this), j)) {}; // case 2
} inst1;
int main() {
struct {
int i;
int j { offsetof(decltype(*this), i) }; // case 3
} inst2;
return 0;
}
它们都不能在 Apple LLVM 版本 6.0 (clang-600.0.57)(基于 LLVM 3.5svn)下编译,并出现错误
error: offsetof requires struct, union, or class type,
'decltype(*this)' (aka '<anonymous struct at ../qxjs3uu/main.cpp:4:4> &') invalid
它还似乎导致 MSVC 19.00.23106.0(x86) 崩溃并出现内部错误:
Compiled with /EHsc /nologo /W4 /c
main.cpp
main.cpp(3): error C2062: type 'S &' unexpected
[...]
main.cpp(4): fatal error C1903: unable to recover from previous error(s); stopping compilation
Internal Compiler Error in c:\tools_root\cl\bin\i386\cl.exe. You will be prompted to send an error report to Microsoft later.
我是否想到了测试用例编写者没有想到的东西?
取消引用指针的结果是一个左值(它本身是一个表达式),因此decltype(*this)
给你输入S&
:
§ 7.1.6.2 [dcl.type.simple]/p4:
表示的类型decltype(e)
定义如下:
— [...]
——否则,如果e
是一个左值,decltype(e)
is T&
, where T
是类型e
;
使用它作为参数offsetof
,您需要从从获取的类型中删除引用decltype()
说明符:
offsetof(std::remove_reference<decltype(*this)>::type, i)
DEMO http://coliru.stacked-crooked.com/a/e80eb98d53edb9bd
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)