[英]How to access base class constructor when using CRTP
I need to insert clone and create member functions to my class hieararchy 我需要在我的类hieararchy中插入clone和create成员函数
class Base
{
protected:
const int x_;
public:
Base() : x_(0) {}
Base(int x) : x_(x) {}
};
I thought that CRTP could be the way how to save some typing and avoid errors. 我认为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)); }
};
Unfortunately I'm not able to access base class constructor to initialize const members. 不幸的是,我无法访问基类构造函数来初始化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;
}
Is there any simple way how to solve this? 有什么简单的方法可以解决这个问题吗?
Simply add all needed constructors to CRTP_Iface
. 只需将所有需要的构造函数添加到
CRTP_Iface
。
public:
CRTP_Iface() : Base() {}
CRTP_Iface( int x ) : Base(x) {}
If using C++11 this gets even easier: 如果使用C ++ 11,这会更容易:
public:
using Base::Base;
Then you have: 然后你有:
class D1 : public CRTP_Iface<D1>
{
public:
D1() : CRTP_Iface() {}
D1(int x) : CRTP_Iface(x) {}
};
... which can be nicer written in C++11: ...可以用C ++ 11更好地编写:
class D1 : public CRTP_Iface<D1>
{
public:
using CRTP_Iface<D1>::CRTP_Iface;
};
(not sure if is needed on either left hand or right hand of ::, AFAIR some complilers like it more strict) (不确定是否需要左手或右手::,AFAIR一些比较严格的编译器)
You can inherit the constructors of class Base
in template CRTP_Iface<>
and then call its constructor in the derived classes: 您可以在模板
CRTP_Iface<>
继承类Base
的构造函数,然后在派生类中调用其构造函数:
template <typename Derived>
class CRTP_Iface : public Base
{
protected:
using Base::Base;
public:
virtual Base *create() const { return new Derived(); }
virtual Base *clone() const { return new Derived(static_cast<Derived const&>(*this)); }
};
class D1 : public CRTP_Iface<D1>
{
public:
D1() : CRTP_Iface() {}
D1(int x) : CRTP_Iface(x) {}
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.