gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 16:42:15 25 4
gpt4 key购买 nike

在未命名结构的类型上创建参数化的方法/函数很容易。在结构的定义之后获取类型也很容易。

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
}

但是是否有任何“魔法”可以允许在结构范围或静态方法中使用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;

这个问题的动机是 question about how to implement a destructor in an unnamed struct .简单的解决方案是将一个命名结构包装在一个未命名的结构中——这样的包装器可以在宏中使用而不会与任何其他类型等发生冲突。

struct { struct S { ... } s; } unnamed;

解决类型访问难题将为激励问题提供不同的解决方案。

最佳答案

也许是这样的?

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

#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;

关于c++ - 如何提取未命名结构的类型以在结构本身内创建新类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32237093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com