是否可以编写一个引用'this'指针的静态断言?我没有c ++ 11可用,并且BOOST_STATIC_ASSERT不起作用。
struct blah
{
void func() {BOOST_STATIC_ASSERT(sizeof(*this));}
};
产地:
error C2355: 'this' : can only be referenced inside non-static member functions
error C2027: use of undefined type 'boost::STATIC_ASSERTION_FAILURE'
在MSVC 2008中。
动机:
#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);}
答案 0 :(得分:2)
问题在于BOOST_STATIC_ASSERT
是宏,它会解析为C ++构造,其中this
关键字具有不同的含义。
要解决这个问题,你可以试试这个:
struct blah
{
void func()
{
const size_t mySize = sizeof(*this);
BOOST_STATIC_ASSERT(mySize);
}
};
答案 1 :(得分:0)
我在GCC explorere中尝试了您的代码,编译得很好。不确定为什么升级版本不起作用,尤其是那个错误。
struct blah
{
int a, b;
void func() {static_assert(sizeof(*this) > 4, "big");} // triggers if you remove b.
};
// -Wall -pedantic --std=c++11