title: Is it possible with C++ to orchestrate the offset of a base class relative to its derived class?
body: <p>Consider the following "black box",</p>
  
  <pre><code>template&lt;std::size_t offset, typename T&gt;
  class BlackBox;
  </code></pre>
  
  <p>Which must have the following feature:</p>
  
  <pre><code>class SomeClass; // This class has a virtual destructor
                   // and a default constructor.
  
  constexpr std::size_t offset = alignof(SomeClass);
  auto bb = new BlackBox&lt;offset, SomeClass&gt;;
  SomeClass* ptr = bb;
  assert((char*)ptr - (char*)bb == offset); // OK(!)
  delete ptr;  // OK - destructs and deletes bb correctly.
  </code></pre>
  
  <p>Here <code>offset</code> is always a non-negative multiple of <code>alignof(SomeClass)</code>, but for the sake of this question you may assume it is exactly one times <code>alignof(SomeClass)</code>.</p>
  
  <p>Furthermore you may assume that <code>alignof(SomeClass) &lt;= alignof(std::max_align_t)</code>.</p>
  
  <p>If it is not possible within (any) C++ standard, then you may assume that the compiler used is a recent version of g++.</p>
  
  <p>I am well aware that this falls under "dirty programming"; nevertheless I kinda "need it". The question is if it is possible (and how) with whatever hacks possible.</p>
  
  <p>I tried the following, <strong>but this does not work</strong>:</p>
  
  <pre><code>template&lt;std::size_t offset, typename T&gt;
  struct Offset {
    typename std::aligned_storage&lt;offset, alignof(T)&gt;::type m_offset;
  };
  
  template&lt;std::size_t offset, typename T&gt;
  class BlackBox : Offset&lt;offset, T&gt;, public T {
    static_assert(offset % alignof(T) == 0, "");
    using T::T;
  };
  </code></pre>
  
  <p>The problem here is that there is no guarantee on how base classes in the case of multiple inheritance are ordered in memory, and as soon as T has a virtual table, it is placed first in memory (by g++) - immediately reducing the offset calculated in the assert to 0.</p>