Social Game Developer wandering in strange dungeon.
Boost::is_base_of
템플릿 프로그래밍을 하다 보면, 문자열이나 사용자 정의 클래스(UDT) 같은 특정 타입에 대한 특수화(specializaiton)를 할 경우가 있다. 그 중에서 가장 헷갈리는 부분이 바로 특정 클래스의 포인터를 템플릿 인자로 받아서 특수화해야 하는 경우인데, boost typetraits 중 하나인 boost::is_base_of를 사용하면 손쉽게 해결할 수 있다.
12345
templatevoidold_algorithm(constT&value){// do generic something}
위와 같은 함수 템플릿에 대해서 Base 클래스의 하위 클래스 포인터를 받았을 때를 위한 특수화를 해야 할 경우, 다음과 같은 패턴을 사용하라. 핵심은 is_base_of::type 이 true_type 또는 false_type 이라는 2 개의 서로 다른 타입을 리턴하며, 이 값을 이용해서 특수화를 한다는 것이다.
1234567891011121314151617181920
templatevoidnew_algorithm(constT&value){typedeftypenameboost::is_base_of::typeis_derived_class;// call implnew_algorithm_impl(value,is_derived_class());}templatevoidnew_algorithm_impl(constT&value,constboost::true_type&){// do specialized for Base class}templatevoidnew_algorithm_impl(constT&value,constboost::false_type&){// do generic something}