2012-07-01 51 views
8

Possible Duplicate:
GCC problem : using a member of a base class that depends on a template argument在模板類中定義的常量

我以爲我熟悉C++,但顯然不夠熟悉。
問題是當你在一個模板類中定義一個常量時,你可以在該類中派生的新類中使用該常量,但不能從該派生類中使用新的模板

例如,GCC說

test.h:18: error: ‘theconstant’ was not declared in this scope

當我嘗試編譯此(簡化)頭文件:

#pragma once 

template <typename T> class base 
{ 
    public: 
    static const int theconstant = 42; 
}; 

class derive1 : public base<size_t> 
{ 
    public: 
    derive1(int arg = theconstant) {} 
}; 

template<typename T> class derive2 : public base<T> 
{ 
    public: 
    derive2(int arg = theconstant) {} // this is line 18 
}; 

所以問題是一個類,derive1,編譯罰款,但其他職業,derive2,這是一個模板專業化,沒有。
現在可能gcc的錯誤還不夠清楚,但我不明白爲什麼derive2中的構造函數與derive1中的構造函數不同。
萬一它很重要,這在編譯頭文件本身時發生,而不是在實例化derive2<type>類型的對象時發生。

我也知道該如何改變才能編譯,所以我並不真正尋找單行代碼作爲答案。我想了解爲什麼發生這種情況!我試圖搜索網頁,但顯然我沒有使用正確的搜索參數。

+0

FWIW,這個代碼在VC++ 2010中編譯得很好。這可能是GCC中的一個bug ... – dsharlet

+0

'derive2(int arg = base :: theconstant){}'編譯得很好。 – jrok

+0

@dsharlet - 不是GCC的一個bug,如規範中所述。 – Flexo

回答

2

我敢肯定,這將幫助你理解:

你的代碼不能編譯:

template<typename T> class derive2 : public base<T> 
{ 
    public: 
    derive2(int arg = theconstant) {} // this is line 18 
}; 

而且理由:

template <> class base<size_t> 
{ 
    public: 
    static const int ha_idonthave_theconstant = 42; 
}; 
derive2<size_t> impossible_isnt_it; 

專業化!編譯器在你的第18行不能確定你不會專注於基地<>,因爲這個常數根本不存在。

+0

這讓我感到很奇怪,我不知道爲什麼它不會出現在我身上......我嘗試過使用專門的模板,只包含具有不同值的同一個成員,並且我無法使其無法工作。好吧。謝謝! –

2

嘗試

template<typename T> class derive2 : public base<T> 
{ 
    public: 
    derive2(int arg = base<T>::theconstant) {} // this is line 18 
}; 

基本上你所指定的範圍不完整的 「theconstant」。

+0

是的,這是在評論中提到的。但是我想明白的是,爲什麼在derived2中認爲這是必要的,而不是在derived1中,即使繼承沒有歧義。示波器不完整? –

+1

我想它必須對「懶惰」模板實例做些什麼。編譯器在分析derive2中的「常量」時有_no_'base'類。一旦你使用的基地,你強迫編譯器「熟悉」基地「」 –

+0

我不得不考慮這一點。 –