Question

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);}
Was it helpful?

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);
   }
};

OTHER TIPS

I tried your code in GCC explorere, it compiled fine. Not sure why the boost version doesn't work, especially with that error.

struct blah
{
  int a, b;
   void func() {static_assert(sizeof(*this) > 4, "big");} // triggers if you remove b.
};

// -Wall -pedantic --std=c++11
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top