'compile time assert'에 해당되는 글 1건

  1. 2009.10.14 [C/C++] 컴파일 타임에 ASSERT 시키기

[C/C++] 컴파일 타임에 ASSERT 시키기

CS/C/C++ 2009. 10. 14. 01:26
원문 : WebKit JavaScriptCore

어떤 클래스의 크기를 제한 할 경우, 컴파일 타임에 클래스 크기를 확인하는 코드.
// tunable parameters
template<size_t bytesPerWord> struct CellSize;

// cell size needs to be a power of two for certain optimizations in collector.cpp
template<> struct CellSize<sizeof(uint32_t)> { static const size_t m_value = 64; };
template<> struct CellSize<sizeof(uint64_t)> { static const size_t m_value = 64; };

const size_t MINIMUM_CELL_SIZE = CellSize<sizeof(void*)>::m_value;
const size_t CELL_ARRAY_LENGTH = (MINIMUM_CELL_SIZE / sizeof(double)) + \
	(MINIMUM_CELL_SIZE % sizeof(double) != 0 ? sizeof(double) : 0);
const size_t CELL_SIZE = CELL_ARRAY_LENGTH * sizeof(double);

#define COMPILE_ASSERT(exp, name) typedef int dummy##name [(exp) ? 1 : -1]
#define ASSERT_CLASS_FITS_IN_CELL(class) \
	COMPILE_ASSERT(sizeof(class) <= CELL_SIZE, class_fits_in_cell)

만약 클래스 크기가 CELL_SIZE보다큰 경우, Compile time error가 발생하게 된다.

error : size of array 'dummyclass_fits_in_cell' is negative.

아, 핵심은

#define COMPILE_ASSERT(exp, name) typedef int dummy##name [(exp) ? 1 : -1]

라는 거죠...
: