从静态方法等效到decltype(*this)?

Jas*_*ton 9 c++ c++11

我有一些宏需要访问当前类的类型,我现在通过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);
    }
};
Run Code Online (Sandbox Code Playgroud)

使用offsetof关键字会产生很多,至少在我自己的工作中.

现在,在锁定this无法通过静态方法访问之前- 实现我只想知道如何ThisStruct从静态方法上下文以通用/宏友好的方式获取类型.我实际上并不需要/想要一个实例,我正在寻找实际上像上面那样没有typedeffing的方式SelfT.

编辑:我可以self在C++中实现自治成员类型吗?- 但我担心钻石问题形成的类都继承了接受的答案Self类.

cmd*_*dLP 5

您可以使用 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);
    }
};
Run Code Online (Sandbox Code Playgroud)

您可以将 Type 重命名为更具描述性的名称。但是您可能会考虑通过将函数移动到继承的结构中,用 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;
};
Run Code Online (Sandbox Code Playgroud)

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