一些C++编译器允许匿名联合和结构作为标准C++的扩展.这有点语法糖,偶尔会非常有帮助.
阻止它成为标准一部分的理由是什么?是否存在技术障碍?一个哲学的?或者仅仅是不足以证明它的合理性?
这是我正在谈论的样本:
struct vector3 {
union {
struct {
float x;
float y;
float z;
};
float v[3];
};
};
Run Code Online (Sandbox Code Playgroud)
我的编译器会接受这个,但它警告"无名结构/联合"是C++的非标准扩展.
在未命名的struct的类型上创建一个参数化的方法/函数很容易.在struct的定义之后获取类型也很容易.
struct Foo {
template <typename T> Foo(T*) { /* we have access to T here */ }
}
template <typename T> void baz(T*) { /* we have access to T here */ }
template<typename T> struct Bar {
/* we have access to T here */
};
void test() {
struct {
Foo foo { this }; // access in a constructor
void test() { baz(this); } // access in a function
} unnamed;
Bar<decltype(unnamed)> bar; // …Run Code Online (Sandbox Code Playgroud) 可以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;
}
Run Code Online (Sandbox Code Playgroud)
它们都没有在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
Run Code Online (Sandbox Code Playgroud)
它似乎也崩溃MSVC 19.00.23106.0(x86)内部错误:
Compiled with /EHsc /nologo /W4 /c
main.cpp …Run Code Online (Sandbox Code Playgroud)