In VS2010, is it possible to use static_assert to verify an assumption about the offset of a variable from the start of a class?

有些话、适合烂在心里 提交于 2019-12-24 09:26:41

问题


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?

来源:https://stackoverflow.com/questions/11313534/in-vs2010-is-it-possible-to-use-static-assert-to-verify-an-assumption-about-the

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!