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

Rei*_*ica 9 c++ struct c++11

在未命名的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; // access after definition
}
Run Code Online (Sandbox Code Playgroud)

但是,是否有任何"魔法"允许unnamed在结构范围或静态方法中使用类型 - 不仅仅在其构造函数/实例方法中或在声明实例之后?结构命名时,这是微不足道的:

// How to make it work with S absent (an unnamed struct) ?
struct S {
  Bar<S> foo; // how to get our type in an unnamed struct?
  static void wrapper(void * instance) {
    static_cast<S*>(instance)->method(); // how to get our type in an unnamed struct?
  }
  void method() { ... }
} would_be_unnamed;
Run Code Online (Sandbox Code Playgroud)

这个问题的动机是关于如何在未命名的结构中实现析构函数的问题.那个简单的解决方案是将一个命名结构包装在一个未命名的结构中 - 这样的包装器然后可以在宏中使用而不会与任何其他类型冲突,等等.

struct { struct S { ... } s; } unnamed;
Run Code Online (Sandbox Code Playgroud)

解决类型访问难题将允许对激励问题采用不同的解决方案.

344*_*442 4

也许是这样的?

这个想法是你实际上有两个未命名的结构。首先,unnamed包含所有实际的代码/数据和内容。然后unnamedWrapper,能够使用decltypeover unnamed,只是一个完全转发(即使对于构造函数!)的包装器unnamed,其唯一的特点是unnamed通过 typedef 导出 的类型。

#include <cstddef>

template<typename T>
size_t templatedSizeof() {
    return sizeof(T);
}

struct {
    char    something;
    short   somethingElse;
    int     moreGargabe;
    long    evenMoreUselessGarbage;
} unnamed;

struct : public decltype(unnamed) {
    typedef decltype(unnamed)   TheType;

    using TheType::TheType; // Use same constructors
} unnamedWrapper;
Run Code Online (Sandbox Code Playgroud)