Posts

Showing posts from 2022

Curiously Recurring Template Pattern(CRTP) 개념과 코드 예제 - Static polymorphism, expression template

Image
 Curiously Recurring Template Pattern  Curiously Recurring Template Pattern (CRTP)[1] 는 derived 클래스를 생성할 때 base 클래스에 derived 클래스의 타입을 template argument로 넘겨주는 패턴을 의미한다. Base 클래스에서 자신을 상속받은 derived 클래스의 타입을 알고 있으면 다양한 기능을 구현할 수 있다.  CRTP는 generic programming에서의 기법이기 때문에 App 개발 코드에 직접적으로 사용되기 보다는 linear algebra, container의 구현 등 코어 라이브러리에서 많이 사용된다. CRTP 패턴은 TensorFlow의 Tensor 모듈, Eigen Tensor, Microsoft  Active Template Library (ATL), Standard Template Library (STL) 구현 등에서 활용되고 있다. CRTP 기본 형태 CRTP 단어를 한글로 바꿔보면 '신기하게 재귀하는 템플릿 패턴' 정도로 번역할 수 있다. CRTP 단어 자체에서 유추해 볼 수 있듯이 Template을 이용한 pattern인데 재귀적인 부분이 있고, 형태가 신기하게 생겼다. 어떤 점이 신기하게 생긴 것일까? 아래 코드에서 는 CRTP의 기본 형태를 보도록 하자. // The Base Class Template template <typename Derived> class BaseTemplate { ... }; // A Derived Class class DerivedClass : public BaseTemplate<DerivedClass> { ... }; // A Derived Class Template template <typename T> class DerivedTemplate : public BaseTemplate<DerivedTemplate<T>...