我想在 C++ 中使用静态多态性来实现模板方法模式。
现在我有两个课程A
,B
它们非常相似。它们具有相同的公共 API 和完全相同的私有数据成员列表。大多数公共成员函数的实现也是相同的,但对于其中一些,这两个类的实现略有不同。
情况看起来有点像这样:
class A {
public:
/* Ctor etc... */
int One() const;
int Two() const;
int Three() const; /* Calls PrivateA() internally */
private:
int PrivateA() const;
int a;
int b;
int c;
};
class B {
public:
/* Ctor etc... */
int One() const; /* Identical to A::One() */
int Two() const; /* Identical to A::Two() */
int Three() const; /* Same as in A::Three() but calls PrivateB() instead of PrivateA() internally */
private:
int PrivateB() const; /* Specific for B */
/* Identical data members (type and semantics) to A */
int a;
int b;
int c;
};
我现在想通过将所有共享代码和数据成员移动到基类并从基类中委托给子类特定的成员函数来减少代码重复。也就是说,像这样:
class Base {
public:
int One() const;
int Two() const;
int Three() const; /* Should delegate to Private() internally */
private:
int a;
int b;
int c;
};
class A : public Base {
private:
int Private() const;
};
class B : public Base {
private:
int Private() const;
};
我知道我可以使用CRTP以类似于以下方式解决此问题:
template<typename T>
class Base {
public:
int One() const;
int Two() const;
int Three() const; /* Should delegate to Private() internally */
private:
int a;
int b;
int c;
};
class A : public Base<A> {
private:
friend class Base<A>;
int Private() const;
int p;
};
class B : public Base<B> {
private:
friend class Base<B>
int Private() const;
int q;
};
template<typename T>
int Base<T>::Three() const {
return static_cast<const T*>(this)->Private();
}
int A::Private() const { return this->p; }
int B::Private() const { return this->q; }
int main() {
A a{};
B b{};
/* Uses shared code from base class */
a.One();
b.One();
/* Base class code statically dispatches to sub-class code via CRTP */
a.Three(); /* Returns value of p */
b.Three(); /* Returns value of q */
return 0;
}
现在谈谈我的问题。
是否可以在不制作Base
模板类的情况下达到相同的结果?我可以使用例如模板成员函数来完成同样的事情吗?
/* Note: no template */
class Base {
public:
int One() const;
int Two() const;
template<typename T>
int Three() const; /* Should delegate to Private() internally */
private:
int a;
int b;
int c;
};