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

C++ 与静态方法中的decltype(*this)等价?,c++,c++11,C++,C++11,我有一些宏需要访问当前类的类型,我目前通过一个干模式来解决这个问题: 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,

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

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);
    }
};
这个关键词的使用带来了很多问题,至少在我自己的工作中

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


编辑:中也有类似的问题,但我担心在继承接受答案的
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);
    }
};
模板
结构类型{using Type=T;};
结构ThisScruct:Type{
INTA;
双b;
//此功能可以复制粘贴到每个
//结构定义,它是从
//键入并包含成员a和b
静态大小总和偏移量(){
typedef-Type::Type SelfT;
返回偏移量(SelfT,a)+偏移量(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;
};
模板
结构集总偏移量{
静态大小总和偏移量(){
类型定义T SelfT;
返回偏移量(SelfT,a)+偏移量(SelfT,b);
}
};
结构ThisStruct:sumOffset{
INTA;
双b;
};

函数
sum_offset
可以通过
thistruct::sum_offset
访问,因为即使是静态函数也会被继承。没有额外的开销,因为既不涉及虚拟函数,也不包含数据成员。

使用_offsetof声明_static _方法意味着什么?您拥有的
typedef
可能是执行此操作的最佳方法。@TonyD在调用这些宏时-我无权访问“this”,因为上下文是静态方法。@Praetorian我使用typedef已经很长时间了;我拒绝相信这是最好的方法:-)!我填了一些具体的东西,用来表示我以前见过这个问题,最后终于找到了——你认为那是一个复制品吗?然而,如果我读得对的话,答案将与涉及到的继承(继承自我的两个类现在涉及到父子关系)决裂。我将再次编辑我的示例。顺便说一句,记忆很好-我多次搜索前面的问题。