相关疑难解决方法(0)

为什么C++不允许使用匿名结构?

一些C++编译器允许匿名联合和结构作为标准C++的扩展.这有点语法糖,偶尔会非常有帮助.

阻止它成为标准一部分的理由是什么?是否存在技术障碍?一个哲学的?或者仅仅是不足以证明它的合理性?

这是我正在谈论的样本:

struct vector3 {
  union {
    struct {
      float x;
      float y;
      float z;
    };
    float v[3];
  };
};
Run Code Online (Sandbox Code Playgroud)

我的编译器会接受这个,但它警告"无名结构/联合"是C++的非标准扩展.

c++ struct unions

87
推荐指数
3
解决办法
5万
查看次数

如何提取未命名结构的类型以在结构本身内创建新类型?

在未命名的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)

c++ struct c++11

9
推荐指数
1
解决办法
569
查看次数

可以偏移与从decltype获得的结构类型一起使用吗?

可以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)

c++ c++11

4
推荐指数
1
解决办法
376
查看次数

标签 统计

c++ ×3

c++11 ×2

struct ×2

unions ×1