2006-05-28

boost::is_base_of

템플릿 프로그래밍을 하다 보면, 문자열이나 사용자 정의 클래스(UDT) 같은 특정 타입에 대한 특수화(specializaiton)를 할 경우가 있다. 그 중에서 가장 헷갈리는 부분이 바로 특정 클래스의 포인터를 템플릿 인자로 받아서 특수화해야 하는 경우인데, boost typetraits 중 하나인 boost::is_base_of를 사용하면 손쉽게 해결할 수 있다.


template
void old_algorithm ( const T & value )
{
  // do generic something
}

위와 같은 함수 템플릿에 대해서 Base 클래스의 하위 클래스 포인터를 받았을 때를 위한 특수화를 해야 할 경우, 다음과 같은 패턴을 사용하라. 핵심은 is_base_of::type 이 true_type 또는 false_type 이라는 2 개의 서로 다른 타입을 리턴하며, 이 값을 이용해서 특수화를 한다는 것이다.


template
void new_algorithm ( const T & value )
{
  typedef typename boost::is_base_of::type is_derived_class;

  // call impl
  new_algorithm_impl(value,is_derived_class());
}

template
void new_algorithm_impl ( const T & value, const boost::true_type& )
{
  // do specialized for Base class
}

template
void new_algorithm_impl ( const T & value, const boost::false_type& )
{
  // do generic something
}


comments powered by Disqus