Curiously Recurring Template Pattern(CRTP)是一种C++中的高级编程技巧,也被称为"奇异递归模板模式"。这种模式看起来有点反直觉,因为它涉及到一个类将自己作为模板参数传递给自己的基类。让我为您详细解释一下这个概念。
#include <iostream>
// Base class template
template <class Derived>
class Animal {
public:
void makeSound() {
// Call the derived class's implementation
static_cast<Derived*>(this)->sound();
}
};
// Derived class
class Dog : public Animal<Dog> {
public:
void sound() {
std::cout << "Woof!" << std::endl;
}
};
// Another derived class
class Cat : public Animal<Cat> {
public:
void sound() {
std::cout << "Meow!" << std::endl;
}
};
int main() {
Dog dog;
Cat cat;
dog.makeSound(); // Outputs: Woof!
cat.makeSound(); // Outputs: Meow!
return 0;
}
584

被折叠的 条评论
为什么被折叠?



