小编nea*_*eam的帖子

constexpr Offsetof 带有指向成员数据的指针

就在这个问题因重复而被驳回之前,大多数(如果不是全部)问题都已接受答案,并带有过时/未定义的行为解决方案。

问题:

有没有办法在编译时获得指向成员数据的指针的偏移量:

  • 不依赖于未定义的行为(nullptr事物)
  • 适用于最新的 gcc 版本(gcc trunk在编译器资源管理器中)
  • 工作方式与offsetof(或类似地,就像提议的代码一样)。

我不在乎:

  • 非标准布局类型
  • msvc 兼容性。(它可能很好,但可选)
  • 对特定编译器有特殊情况

问题:

使用 GCC 的主干版本,以下技巧(hack)不起作用:

#include <cstdint>
#include <cstddef>

namespace detail
{
    // The union stuff is for CLang to avoid creating warnings
    template<typename T, auto MPtr>
    struct offsetof_ptr_helper
    {
        union helper_t { int i = 0;  T value; };
        static constexpr helper_t v = {};
        static constexpr size_t sz = sizeof
        (uint8_t[
            (uint8_t *)&(v.value.*MPtr) -
            (uint8_t *)&v.value
        ]);
    };
} …
Run Code Online (Sandbox Code Playgroud)

c++

8
推荐指数
1
解决办法
402
查看次数

标签 统计

c++ ×1