一、CRTP
什么是CRTP?Curiously Recurring Template Pattern ,奇异递归模板模式,这名字有点奇异。它也被叫做F-bound多态性(F - bounded quantification),也叫做“倒置继承”。听它的名字就大致明白了,正常的继承通过是子类继承父类,然后再各种操作。但CRTP是通过模板的方式,由子类继承父类,但父类的模板参数又是子类的一种奇怪的方式。
用脚想也知道这种方式一定不是正常的标准创建出来的,没有人闲的会这么做。它是一个国外的牛人Jim Coplien在 1995 年独立创造的,后来 1995 年由 Jan Falkin在开发ATL时独立发现了这种情况。一般来说,刚刚接触这个技术的人大多会把其当成一种错误,但在运行后,才会发现它确实是可以正确工作的。
这个技术应用主要也是在模板的元编程中的实现的,在c++中,好多的技术都是为了元编程服务的,另外就是在一些需要实现编译期(静态)多态的情况下使用。在C++11中的std::enable_shared_from_this就是这个技术的一个实际应用的例子。
二、分析说明
看一下CRTP的一个基本样子:
// The Curiously Recurring Template Pattern (CRTP)
template <class T>
class Base
{
// 基类方法可以通过模板继承的方式来访问继承类的成员
};
class Derived : public Base<Derived>
{
};
再看一下智能指针中对自己的使用:
class Base : public std::enable_shared_from_this<Base>
{
public:
Base() { }
~Base() { }
void Get()
{
Do(shared_from_this());
}
};
void Do(std::shared_ptr<Base> ptr) {}
CRTP一般具有以下几个特点:
1、父类为模板类,其模板参数是子类
2、子类的继承方式如上面两个例子的形制
3、一般来说,父类的函数会通过静态类型转换(static_cast<>)将父类指针转为子类指针。从而在编译期完成绑定。
看了这三点,其实就可以和普通继承中动态绑定比较了。虽然CRTP看上去有点古怪,但是它解决了传统的动态绑定的速度慢,运行期才能实现两个主要的问题。
三、应用
通过上面的分析,基本明白了CRTP的作用,那么其主要的应用场景有哪些呢:
1、静态多态
#include <iostream>
template <class T>
class Base
{
public:
void Display()
{
static_cast<T*>(this)->Data();
}
static void Call()
{
T::Call();
}
};
class Derived : public Base<Derived>
{
public:
void Data() { std::cout << "Derived function :Data()" << std::endl; };
static void Call() { std::cout << "Derived function :Call()" << std::endl; };
};
int main()
{
Derived d;
Base<Derived> *b = &d;
b->Display();
b->Call();
}
看上去和普通的继承没啥区别,但是最大的区别在于不再运行时才绑定。
2、类似于智能指针的使用
template <typename T>
struct refcounter
{
static int ref_ ;
static int release_ ;
refcounter()
{
++ref_;
++release_;
}
refcounter(const refcounter&)
{
++ref_;
++release_;
}
protected:
~refcounter()
{
--release_;
}
};
template <typename T> int refcounter<T>::ref_(0);
template <typename T> int refcounter<T>::release_(0);
class A : refcounter<A>
{
public:
void GetCounter()
{
std::cout << "cur ref is:"<< ref_ << " "<< release_ << std::endl;
}
};
class B : refcounter<B>
{
public:
void GetCounter()
{
std::cout << "cur ref is:" << ref_ << " " << release_ << std::endl;
}
};
void TestRef()
{
A a;
B b;
A a1(a);
a1.GetCounter();
b.GetCounter();
}
int main()
{
TestRef();
return 0;
}
3、如Kotlin等的链式编程
template <typename ConcretePrinter>
class Printer
{
public:
Printer(std::ostream& pstream) : stream_(pstream) {}
template <typename T>
ConcretePrinter& print(T&& t)
{
stream_ << t;
return static_cast<ConcretePrinter&>(*this);
}
template <typename T>
ConcretePrinter& println(T&& t)
{
stream_ << t << std::endl;
return static_cast<ConcretePrinter&>(*this);
}
private:
std::ostream& stream_;
};
enum Color
{
red,blue,green
};
class CoutPrinter : public Printer<CoutPrinter>
{
public:
CoutPrinter() : Printer(std::cout) {}
CoutPrinter& SetConsoleColor(Color c)
{
return *this;
}
};
void TestChain()
{
CoutPrinter().print("Hello ").SetConsoleColor(Color::red).println("Printer!");
}
int main()
{
TestChain();
return 0;
}
一般来说在c++里很少出现这种链式的代码。这里通过CRTP实现了一种多态的链式式编程。
4、多态拷贝构造(Polymorphic copy construction)
class AbstractShape {
public:
virtual ~AbstractShape() = default;
virtual std::unique_ptr<AbstractShape> clone() const = 0;
//virtual void Show() = 0;
};
// This CRTP class implements clone() for Derived
template <typename Derived>
class Shape : public AbstractShape {
public:
std::unique_ptr<AbstractShape> clone() const override {
return std::make_unique<Derived>(static_cast<Derived const&>(*this));
}
protected:
// We make clear Shape class needs to be inherited
Shape() = default;
Shape(const Shape&) = default;
Shape(Shape&&) = default;
};
// Every derived class inherits from CRTP class instead of abstract class
class Square : public Shape<Square>
{
public:
void Show() override{ std::cout << "is Square!" << std::endl; }
};
class Circle : public Shape<Circle>
{
public:
void Show() override{ std::cout << "is Circle!" << std::endl; }
};
void TestClone()
{
std::unique_ptr<Square> ptrS = std::make_unique<Square>();
std::unique_ptr<Circle> ptrC = std::make_unique<Circle>();
auto p = ptrS->clone();
std::unique_ptr<AbstractShape> pc = ptrC->clone();
//p->Show();
//pc->Show();
}
int main()
{
TestClone();
return 0;
}
这种应用主要是在父子类中对对象Clone(利用父指针创建子类的副本)时使用,这样做的好处就是把每个类中的重复的代码去除,只写一套就可以了。
但是上面的应用有一个问题,就是在容器处理中,不能实现类似存储同一父类指针来实现动态的子类存储。但是也有解决的方法,其实就是一种妥协的方式,把上面的代码注释部分解开,增加一个需要重载的函数,再运行,是不是就达到了目的。如果觉得这种方法不直接,可以在Shape中也把智能指针的处理改成对多态函数的重载,然后直接象普通的类继承方式使用,通过指针存储到容器中即可使用。而使用现在这种方式和普通的继承是一致的。
四、总结
在实际工程中从来没直接用过CRTP(当然std::enable_shared_from_this不算),其实就是元编程的应用太少,所以导致对其比较生疏。还是要多把一些基础的知识认真的学习弄懂,以后在元编程的开发过程中,才可能游刃有余。
新年来了,努力吧!