2011-10-21 32 views
2

我嘗試使用CRTP有小的變化。我有一個派生類模板,並希望將其應用於多個基類。但是,這要麼不可能,要麼我無法正確理解語法。下面的代碼不能編譯,但希望能夠說明我想實現的目標:具有參數化基類的C++ CRTP?

template <class Derived> struct BaseCats { /* ... */ }; 
template <class Derived> struct BaseDogs { /* ... */ }; 
// .... 
template <class Derived> struct BaseN { /* ... */ }; 

template <template <class> class Base> 
struct Wrapper 
    : 
    Base<Wrapper> // compile error - Wrapper is not a complete type 
{ 
    Wrapper(int n) 
    { 
     // I do not want to rewrite or forward this 
     // constructor or Wrapper's operators 
    } 
}; 

typedef Wrapper<BaseCats> Cats; 
typedef Wrapper<BaseDogs> Dogs; 
// ... 
typedef Wrapper<BaseN> MyTypeN; 

可以這樣做嗎?

編輯:

什麼我想在這裏實現?

我改名一些代碼上方使用一個「狗和貓」的比喻。有可能存在的功能,如:

void BaseCats<Derived>::print() const 
{ 
    std::cout << (static_cast<const Derived *>this)->n << " cats\n"; 
} 

Wrapper將包含構造函數和共有的狗和貓的運營商。基類具有專業化的倒轉多態性。這樣做的原因是,構造函數和操作符不必爲每個專業化而重寫或轉發。

+0

什麼是你想達到這樣的設計呢? – Nawaz

+2

你意識到你正試圖使'Base'從'Derived'本身從'Base'本身從'Derived'等派生派生得出?你應該解釋你的目標是什麼,而不是你如何實現它,這樣我們才能提出替代方案。 –

+0

@Luc,哎呀,一個有趣的設計固定 – paperjam

回答

4

你的編譯錯誤,可以通過這個來解決:

Base<Wrapper<Base> > 

你忘了模板參數。

+0

是啊,我居然沒想到的,但認爲我不得不在寫'基地<包裝<基地<包裝<基地<包裝<基地>>>>>>>' – paperjam

+0

@paperjam只要基礎不繼承包裝,就不會發生這種情況。 – Pubby