1

Here is a simplified example:

class A
{
    enum {OFFSET = 4};  //Due to packing

    bool m_bool;
};

template<class T>
class B : public A
{
    MyClass<T> m_class;
};

Now supposing that class A can make use of a subset of MyClass's functionality via a base-class of MyClass, what I wish to do is verify an assumption about the location of 'm_class' with respect to an instance of class A.

I have tried the following code from within a member-function of class B, but it gives an error ("expected constant expression"):

static_assert ((byte *)nullptr + OFFSET ==
    (byte *)&((B<T> *)nullptr)->m_class, "Error 'm_class' incorrectly located!");

Is this simply too ambitious for the current version of the compiler?

Coder_Dan
  • 1,815
  • 3
  • 23
  • 31
  • Nothing has a member `m_array`. To you mean `((B*)nullptr)->m_bool` ? – Tim Jul 03 '12 at 15:05
  • Thanks Tim - that was an omission in the translation of my real-world code into something that I was hoping might be more readable. I've fixed it now. – Coder_Dan Jul 03 '12 at 15:08
  • 3
    Is the standard macro `offsetof` good enough? –  Jul 03 '12 at 15:12
  • Great tip, @hvd! The following code works: static_assert (offsetof (B, m_class) == OFFSET, "Error 'm_class' incorrectly located!"); – Coder_Dan Jul 03 '12 at 15:17
  • Why on Earth do you want to do this? I assume you end up using `reinterpret_cast` and all that's going to happen is sometime two years from now your code will break in some obscure way and take two weeks to trace back to this design. – Mark B Jul 03 '12 at 15:36
  • 1
    @Mark B - The static_assert is intended to ensure that the code does not break in an obscure way. It all boils down to an internal coding guideline that suggests that templated classes should use a non-templated base-class for any functionality that doesn't require the template parameter. The 'MyClass' item in my case has a non-templated base-class, which can be used by the class 'A' for certain accessors, but class 'A' cannot itself contain the 'MyClass' because that is reliant upon the template parameter. This code is performance-critical. I hope this explains a little. – Coder_Dan Jul 03 '12 at 16:22
  • @hvd offsetof is usefull indeed http://en.wikipedia.org/wiki/Offsetof maybe you can turn it into an answer? – aka.nice Aug 16 '12 at 09:26
  • @aka.nice My suggestion here was wrong, unfortunately. `offsetof` required a POD struct. Having a base class means the class isn't an aggregate, and the class not being an aggregate means it isn't a POD struct. `offsetof` may work here in practise on specific compilers, but it's undefined in standard C++. –  Aug 16 '12 at 17:26
  • @hvd OK, I used it with POD struct like Mr Jourdain. Thanks, I learned some slang http://stackoverflow.com/questions/146452/what-are-pod-types-in-c – aka.nice Aug 16 '12 at 17:40

0 Answers0