-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
3 changed files
with
72 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,2 +1,13 @@ | ||
## CRTP 奇异递归模板模式 (Curiously recurring Template Pattern) | ||
|
||
### CRTP (Curiously recurring Template Pattern) | ||
1980年代作为 F-bound polymorphism 被提出。Jim Coplien 于 1995 年称之为 CRTP 。 | ||
|
||
CRTP 在 C++ 中主要有两种用途: | ||
|
||
- 静态多态(static polymorphism) | ||
- 添加方法同时精简代码 | ||
|
||
|
||
### Reference | ||
|
||
- https://zhuanlan.zhihu.com/p/54945314 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
#include <iostream> | ||
using namespace std; | ||
|
||
template <typename Child> | ||
struct Base { | ||
void interface() { | ||
static_cast<Child*>(this)->implementation(); | ||
} | ||
}; | ||
|
||
struct Derived : Base<Derived> { | ||
void implementation() { | ||
cerr << "Derived implementation\n"; | ||
} | ||
}; | ||
|
||
int main() { | ||
Derived d; | ||
d.interface(); // Prints "Derived implementation" | ||
|
||
return 0; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
#include <iostream> | ||
using namespace std; | ||
|
||
template <typename Child> | ||
class Animal { | ||
public: | ||
void Run() { | ||
static_cast<Child *>(this)->Run(); | ||
} | ||
}; | ||
|
||
class Dog : public Animal<Dog> { | ||
public: | ||
void Run() { | ||
cout << "Dog Run" << endl; | ||
} | ||
}; | ||
|
||
class Cat : public Animal<Cat> { | ||
public: | ||
void Run() { | ||
cout << "Cat Run" << endl; | ||
} | ||
}; | ||
|
||
template <typename T> | ||
void Action(Animal<T> &animal) { | ||
animal.Run(); | ||
} | ||
|
||
int main() { | ||
Dog dog; | ||
Action(dog); | ||
|
||
Cat cat; | ||
Action(cat); | ||
return 0; | ||
} |