gpt4 book ai didi

c++ - 与静态方法中的 decltype(*this) 等价?

转载 作者:可可西里 更新时间:2023-11-01 16:48:37 29 4
gpt4 key购买 nike

我有一些宏需要访问当前类的类型,目前我通过违反 DRY 的模式解决了这个问题:

struct ThisScruct{
int a;
double b;
//example static method using this - purely example - not full usecase

static size_t sum_offsets(){
typedef ThisStruct SelfT;
return offsetof(SelfT, a) + offsetof(SelfT, b);
}
};

这在使用 offsetof 时经常出现。关键字,至少在我自己的作品中是这样。

现在,在您锁定 this 无法通过静态方法访问之前 - 意识到我只想知道如何以通用/宏友好的方式获取类型 ThisStruct来自静态方法上下文。我实际上并不需要/想要一个实例,我正在寻找无需类型定义 SelfT 即可像上面那样实际工作的方式。

编辑:Can I implement an autonomous self member type in C++? 中提出了类似的问题- 但我担心从接受的答案的 Self 类继承的类形成菱形继承(钻石问题)。

最佳答案

您可以使用 CRT 模式来访问类型名,您只需要在继承列表中指定它即可。

    template<class T>
struct Type { using type = T; };

struct ThisScruct : Type<ThisStruct> {
int a;
double b;

// this function can be copy-pasted into every
// struct definition, which is inherited from
// Type and contains the members a and b
static size_t sum_offsets(){
typedef Type::type SelfT;
return offsetof(SelfT, a) + offsetof(SelfT, b);
}
};

您可以将类型重命名为更具描述性的名称。但是您可能会考虑通过将函数移动到继承的结构中,用 CRT 模式完全替换此功能。

    template<class T>
struct SumOffsets {
static size_t sum_offsets(){
typedef T SelfT;
return offsetof(SelfT, a) + offsetof(SelfT, b);
}
};

struct ThisStruct : SumOffsets<ThisStruct> {
int a;
double b;
};

sum_offsets 函数可以被ThisStruct::sum_offsets 访问,因为即使是静态函数也是继承的。没有额外的开销,因为既不涉及虚函数也不 SumOffsets 有数据成员。

关于c++ - 与静态方法中的 decltype(*this) 等价?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30228913/

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