I need to insert clone and create member functions to my class hieararchy
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.
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.
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
.
public:
CRTP_Iface() : Base() {}
CRTP_Iface( int x ) : Base(x) {}
If using C++11 this gets even easier:
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:
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)
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments