<html>
    <head>
      <base href="https://bugs.llvm.org/">
    </head>
    <body><table border="1" cellspacing="0" cellpadding="8">
        <tr>
          <th>Bug ID</th>
          <td><a class="bz_bug_link 
          bz_status_NEW "
   title="NEW - bad code with hand-crafted offsetof"
   href="https://bugs.llvm.org/show_bug.cgi?id=40831">40831</a>
          </td>
        </tr>

        <tr>
          <th>Summary</th>
          <td>bad code with hand-crafted offsetof
          </td>
        </tr>

        <tr>
          <th>Product</th>
          <td>clang
          </td>
        </tr>

        <tr>
          <th>Version</th>
          <td>unspecified
          </td>
        </tr>

        <tr>
          <th>Hardware</th>
          <td>PC
          </td>
        </tr>

        <tr>
          <th>OS</th>
          <td>Linux
          </td>
        </tr>

        <tr>
          <th>Status</th>
          <td>NEW
          </td>
        </tr>

        <tr>
          <th>Severity</th>
          <td>enhancement
          </td>
        </tr>

        <tr>
          <th>Priority</th>
          <td>P
          </td>
        </tr>

        <tr>
          <th>Component</th>
          <td>C++
          </td>
        </tr>

        <tr>
          <th>Assignee</th>
          <td>unassignedclangbugs@nondot.org
          </td>
        </tr>

        <tr>
          <th>Reporter</th>
          <td>stsp2@yandex.ru
          </td>
        </tr>

        <tr>
          <th>CC</th>
          <td>blitzrakete@gmail.com, dgregor@apple.com, erik.pilkington@gmail.com, llvm-bugs@lists.llvm.org, richard-llvm@metafoo.co.uk
          </td>
        </tr></table>
      <p>
        <div>
        <pre>As offsetof doesn't work with template arguments,
I have to create the one by hands:
---
#include <cstddef>
#include <iostream>

class L {};
template <typename T, L (T::*M)[0]>
struct offset_of {
    constexpr operator size_t() const {
        return (std::uintptr_t)&(((T*)nullptr)->*M);
    }
};
template <typename T, L (T::*M)[0]>
struct B {
    char aa[10];
    static const int off = offset_of<T, M>();
};

struct A {
    char a;
    L _mark[0];
    B<A, &A::_mark> b;
};

int main()
{
    A a;
    std::cout << "size " << sizeof(A) << " off " << a.b.off << std::endl;
    return 0;
}
---

This example works perfectly with gcc:
size 11 off 1

But behaves badly when compiled with clang:
size 1 off 1
(and sometimes even segfaults, it seems)

Besides fixing the bug, I wonder if it would be
possible to somehow fix offsetof() to allow the
use of templated args? Otherwise people have to
apply the horrible hacks like this.</pre>
        </div>
      </p>


      <hr>
      <span>You are receiving this mail because:</span>

      <ul>
          <li>You are on the CC list for the bug.</li>
      </ul>
    </body>
</html>