2013-02-07 94 views
1

下一個代碼工作正常(這是我的另一個問題的過於簡化版本,類型更長,更深,更模板):獲取模板基類的類型

template<class C> 
struct Base 
{}; 

template<class C> 
struct Derived : public Base<C> 
{ 
    Derived() : Base<C>() 
    {} 
}; 

但是,我怎麼能打電話沒有「寫」基類的完整類型的基類構造函數?例如,我試過類似的東西:

template<class C> 
struct Base 
{ 
    typedef Base base_type; 
}; 

template<class C> 
struct Derived : public Base<C> 
{ 
    Derived() : base_type() {} 
}; 

int main() 
{ 
    Derived<void> b; 
} 

但是「base_type」未被識別。該GCC拋出的消息是:

test3.cpp: In constructor 'Derived<C>::Derived()': 
    test3.cpp:100:17: error: class 'Derived<C>' does not have any field 
    named 'base_type' 

爲了解決它,我必須寫在構造Base<C>::base_type,但這會使得base_type本身的存在無關。

難道我的寫作拯救運動是不可能的嗎?

而且,爲什麼base_type在構造函數中找不到,然而這工作正常嗎?

int main() 
{ 
    Derived<void>::base_type b; 
} 

編輯:隨着@Jack Aidley的評論,我發現一個簡單的別名來獲得基類的類型,最好的形式是:

template<typename C> struct Base {}; 

template<typename C, typename Base> 
struct Derived_impl : public Base 
{ 
    Derived_impl() : Base() 
    {} 
}; 

template<typename C> 
using Derived = Derived_impl<C, Base<C> >; 

int main() 
{ 
    Derived<void> b; 
} 
+1

任何你不能做的原因'template struct派生:public Base '? –

+0

這似乎是個好主意。謝謝。 –

回答

2

根據標準

當查找模板 定義中使用的名稱聲明時,通常的查找規則(3.4.1,3.4.2)用於 非獨立名稱。推遲依賴於模板 參數的名稱查找,直到已知實際模板參數爲 (14.6.2)。

這意味着,你必須告訴編譯器,這base_typeBase類,依賴的C。您可以使用,例如,這樣的:

template<class C> 
struct Derived : public Base<C> 
{ 
    using typename Base<C>::base_type; 

    Derived() : base_type() {} 
}; 

或本

template<class C> 
struct Derived : public Base<C> 
{ 
    Derived() : Derived<C>::base_type() {} 

    // or, as you already told, Base<C>::base_type() 
}; 
2

你總是可以做到這一點:

template<class C> 
struct Base 
{ 
}; 

template<class C> 
struct Derived : public Base<C> 
{ 
    typedef Base<C> base_type; // define here 

    Derived() : base_type() {} 
}; 

有道理的,如果你指的是基本類型中Derived ...