C++ 使用CRTP时如何访问基类构造函数
我需要将克隆和创建成员函数插入到我的类层次结构中C++ 使用CRTP时如何访问基类构造函数,c++,crtp,C++,Crtp,我需要将克隆和创建成员函数插入到我的类层次结构中 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 *crea
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)); }
};
模板
类别CRTP_Iface:公共基础
{
公众:
虚拟基*create()常量{返回新的派生();}
虚拟基*clone()常量{返回新的派生(静态_cast(*this));}
};
不幸的是,我无法访问基类构造函数来初始化常量成员
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;
}
D1类:公共CRTP
{
公众:
D1():Base(){}
D1(int x):基(x){}
};
D2类:公共交通工具
{
公众:
D2():x_0{}
D2(int x):x_ux(x){}
};
int main()
{
D1 a;
D2 b;
返回0;
}
有什么简单的方法可以解决这个问题吗?只需将所有需要的构造函数添加到
CRTP\u 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) {}
};
D1类:公共CRTP
{
公众:
D1():CRTP_Iface(){}
D1(int x):CRTP_Iface(x){}
};
。。。用C++11编写哪个更好:
class D1 : public CRTP_Iface<D1>
{
public:
using CRTP_Iface<D1>::CRTP_Iface;
};
D1类:公共CRTP
{
公众:
使用CRTP_Iface::CRTP_Iface;
};
(不确定在::,的左侧或右侧是否需要,因为有些编译器喜欢它更严格)您可以在template
CRTP\u 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) {}
};
模板
类别CRTP_Iface:公共基础
{
受保护的:
使用Base::Base;
公众:
虚拟基*create()常量{返回新的派生();}
虚拟基*clone()常量{返回新的派生(静态_cast(*this));}
};
D1类:公共交通工具
{
公众:
D1():CRTP_Iface(){}
D1(int x):CRTP_Iface(x){}
};
如果执行'D1 a;,代码中会发生什么;自动c=a.create();删除c;'@凤王井一号应该为
基地添加一个虚拟析构函数
: