[英]How to access base class constructor when using 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一些比較嚴格的編譯器)
您可以在模板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.