CTAssert

Tags:

trax님 집에서 보고 퍼옴.

#include <iostream>

using namespace std;

template <bool> struct CTAssert;
template <> struct CTAssert<true> { };

int main()
{
    CTAssert<sizeof(int)==3>();
    return EXIT_SUCCESS;
}

이 경우 에러가 납니다. 왜냐면 CTAssert<false> 라는 것이 없으니까. 물론 template<bool> CTAssert 는 존재하지만, 이는 declaration 으로만 존재하고 definition은 빠져있어서 false에 대한 클래스 생성은 불가능하며, 이는 순전히 template<> CTAssert<true> 의 specialization을 위한 forward declaration에 불과함. 만약 CTAssert 를, template<bool> struct CTAssert { }; 라고 한다면 CTAssert<false> 가 나와도 컴파일에 문제가 없게 됩니다.

이런 assertion의 장점은 cassert(assert의 C++버젼입니다. stdlib는 cstdlib이듯이..)나 assert 와 달리 컴파일 타임이라는 것..

어렵군요.

참고할 만한 글.
http://mkseo.pe.kr/archives/001279.html 에서, template의 친구들 부분.
http://www.cprogramming.com/tutorial/template_specialization.html

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *