【问题标题】:equivalence to decltype(*this) from a static method?与静态方法的 decltype(*this) 等价?
【发布时间】:2019-05-11 23:33:21
【问题描述】:

我有一些宏需要访问当前类的类型,而我目前通过违反 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 类时会形成菱形问题。

【问题讨论】:

  • declare_static_methods_using_offsetof 是什么意思?您拥有的typedef 可能是这样做的最佳方式。
  • @TonyD 调用这些宏时 - 我无权访问“this”,因为上下文是静态方法。
  • @Praetorian 我已经使用 typedef 很长时间来做到这一点;我拒绝相信这是最好的方法:-)!我为 declare_static_methods_using_offsetof 填写了一些具体的内容
  • 我知道我以前见过这个问题,终于找到了 - stackoverflow.com/q/21143835/241631 你会认为这是重复的吗?
  • @Praetorian 从表面上看我愿意;但是,如果我没看错的话,那里的答案将会因涉及继承而中断(继承 Self 的两个类现在涉及父子关系)。我将再次编辑我的示例。顺便说一句,记忆力很好 - 我多次搜索先前的问题。

标签: c++ c++11


【解决方案1】:

你可以使用 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);
    }
};

您可以将 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;
};

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-06-30
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    • 2012-04-26
    相关资源
    最近更新 更多