한 가지 가능한 사용은 기능의 기본 버전이 정의되어 CRTP 프레임 워크를 구현하기위한 수 :
#include <iostream>
//This could be any higher-order function.
template<typename T>
class CallFiveTimes {
protected:
void docalls() const {
for(int i(0); i != 5; ++i) static_cast<T const*>(this)->callme();
}
//Default implementation. If a lot
//of different functionality were required of `T`
//then defaults could make `T` easier to write.
void callme() const {
std::cout << "Default implementation.\n";
}
};
class Client : CallFiveTimes<Client> {
public:
void useFramework() {
docalls();
}
private:
friend struct CallFiveTimes<Client>;
//This redefinition will be used.
void callme() const {
std::cout << "Client implementation.\n";
}
};
class LazyClient : CallFiveTimes<LazyClient> {
public:
void useFramework() {
docalls();
}
friend struct CallFiveTimes<LazyClient>;
};
int main() {
Client c;
c.useFramework(); //prints "Client Implementation" five times
LazyClient lc;
lc.useFramework(); //prints "Default Implementation" five times
}
나는이 연습에서 수행 본 적이 있지만, 어떤 경우에 고려 가치가있을 수 있습니다.
이것이 특정 교재의 질문인지 묻습니다. 나는 단지 궁금하다! – Yakk
CRTP에 대해 들어 보셨습니까? 만약 당신이 익숙하지 않다면 그것을 보아라. – Mehrdad
@ Yakk - Nope, 나는 개발 중에 생각했다. – Unsigned