c – 使用CRTP时如何访问基类构造函数
作者:互联网
我需要在我的类hieararchy中插入clone和create成员函数
class Base
{
protected:
const int x_;
public:
Base() : x_(0) {}
Base(int x) : x_(x) {}
};
我认为CRTP可能是如何节省一些打字并避免错误的方法.
template <typename Derived>
class CRTP_Iface : public Base
{
public:
virtual Base *create() const { return new Derived(); }
virtual Base *clone() const { return new Derived(static_cast<Derived const&>(*this)); }
};
不幸的是,我无法访问基类构造函数来初始化const成员.
class D1 : public CRTP_Iface<D1>
{
public:
D1() : Base() {}
D1(int x) : Base(x) {}
};
class D2 : public CRTP_Iface<D2>
{
public:
D2() : x_(0) {}
D2(int x) : x_(x) {}
};
int main()
{
D1 a;
D2 b;
return 0;
}
有什么简单的方法可以解决这个问题吗?
解决方法:
只需将所有需要的构造函数添加到CRTP_Iface即可.
public:
CRTP_Iface() : Base() {}
CRTP_Iface( int x ) : Base(x) {}
如果使用C 11,这会更容易:
public:
using Base::Base;
然后你有:
class D1 : public CRTP_Iface<D1>
{
public:
D1() : CRTP_Iface() {}
D1(int x) : CRTP_Iface(x) {}
};
…可以用C 11更好地写出来:
class D1 : public CRTP_Iface<D1>
{
public:
using CRTP_Iface<D1>::CRTP_Iface;
};
(不确定是否需要左手或右手::,AFAIR一些比较严格的编译器)