Search code examples
c++boostthisstatic-assert

Referring to this pointer in a static assert?


Is it possible to write a static assert referring to the 'this' pointer? I do not have c++11 available, and BOOST_STATIC_ASSERT doesn't work.

struct blah
{
   void func() {BOOST_STATIC_ASSERT(sizeof(*this));}
};

Produces:

error C2355: 'this' : can only be referenced inside non-static member functions
error C2027: use of undefined type 'boost::STATIC_ASSERTION_FAILURE'

In MSVC 2008.

Motivation:

#define CLASS_USES_SMALL_POOL() \
   void __small_pool_check()     {BOOST_STATIC_ASSERT(sizeof(*this) < SMALL_MALLOC_SIZE;} \
   void* operator new(size_t)    {return SmallMalloc();}                                  \
   void operator delete(void* p) {SmallFree(p);}

Solution

  • The problem is that BOOST_STATIC_ASSERT is a macro, it resolves into a C++ construct, in which your this keyword has different meaning.

    To work this around you may try this:

    struct blah
    {
       void func()
       {
          const size_t mySize = sizeof(*this);
          BOOST_STATIC_ASSERT(mySize);
       }
    };