非常具体地说,可以使用 CRTP 代替具有虚函数的基类来实现模板方法模式,而无需虚函数调用开销。
使用虚函数,TMP 看起来像这样:
class ProvidesMethod {
protected:
void Method() {
// do something
Part1();
// do something else
Part2();
// do something final
}
private:
virtual void Part1() = 0;
virtual void Part2() = 0;
};
class ExposesMethod : private ProvidesMethod {
public:
using ProvidesMethod::Method;
private:
void Part1() {
// first part implementation
}
void Part2() {
// second part implementation
}
};
使用 CRTP,它看起来像这样:
template <typename Derived>
class ProvidesMethod {
protected:
void Method() {
// do something
self().Part1();
// do something else
self().Part2();
// do something final
}
private:
Derived& self() { return *static_cast<Derived*>(this); }
const Derived& self() const { return *static_cast<const Derived*>(this); }
};
class ExposesMethod : private ProvidesMethod<ExposesMethod> {
public:
using ProvidesMethod<ExposesMethod>::Method;
private:
friend class ProvidesMethod<ExposesMethod>;
void Part1() {
// first part implementation
}
void Part2() {
// second part implementation
}
};