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;
}
在苹果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.
我有没有想到测试用例编写者没有想到的东西?
offsetof
是如此挑剔,一个简单的引用就能让它失去平衡 :) - Kuba hasn't forgotten Monicaoffsetof
的错;更多的是因为引用很奇怪。 - The Paramagnetic Croissant&
符号。但是,为了看到它,必须非常仔细地阅读以下错误信息:error: offsetof requires struct, union, or class type, 'decltype(*this)' (aka '<anonymous struct at ../qxjs3uu/main.cpp:4:4> &') invalid
! - Toby Speight