问题描述
可以 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),错误
错误:offsetof需要struct,union或类类型,
'decltype(* this)'(aka'< anonymous struct at ../qxjs3uu/main.cpp:4:4>&')invalid
它也似乎崩溃MSVC 19.00.23106.0(x86)与内部错误:
编译/ EHsc / nologo / W4 / c
main.cpp
main.cpp(3):错误C2062:类型'S&'意外
[... ]
main.cpp(4):致命错误C1903:无法从先前错误中恢复;停止编译
c:\tools_root\cl\bin\i386\cl.exe中的内部编译器错误。稍后将提示您向Microsoft发送错误报告。
我想到了没有测试用例写作者想到的东西吗?
解引用指针的结果是一个左值(并且它本身是一个表达式),因此 decltype(* this)
为您提供类型 S&
:
§7.1.6.2 [dcl.type.simple] / p4
它作为 offsetof
的参数,您需要从从 decltype()
获取的类型中删除引用,说明符:
offsetof(std :: remove_reference< decltype(* this)> :: type,i)
Can offsetof
be used with a type obtained through decltype
? Is either of those cases valid 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;
}
None of it compiles under Apple LLVM version 6.0 (clang-600.0.57) (based on LLVM 3.5svn), with the error
error: offsetof requires struct, union, or class type,
'decltype(*this)' (aka '<anonymous struct at ../qxjs3uu/main.cpp:4:4> &') invalid
It also seems to crash MSVC 19.00.23106.0(x86) with an internal error:
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.
Did I think of something that no test case writers thought of?
The result of dereferencing a pointer is an lvalue (and itself is an expression), thus decltype(*this)
gives you type S&
:
§ 7.1.6.2 [dcl.type.simple]/p4:
To use it as an argument to offsetof
, you'd need to remove a reference from a type obtained from the decltype()
specifier:
offsetof(std::remove_reference<decltype(*this)>::type, i)
这篇关于可以将offsetof与从decltype获取的struct类型一起使用吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!