Skip to content

Commit

Permalink
2021-04-24 20:57:01 CST W16D6
Browse files Browse the repository at this point in the history
  • Loading branch information
aggresss committed Apr 24, 2021
1 parent d721b0b commit 835ef04
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 1 deletion.
13 changes: 12 additions & 1 deletion metaprogramming/template_recursion/README.md
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
22 changes: 22 additions & 0 deletions metaprogramming/template_recursion/hello_01.cpp
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;
}
38 changes: 38 additions & 0 deletions metaprogramming/template_recursion/hello_02.cpp
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;
}

0 comments on commit 835ef04

Please sign in to comment.