2010-11-17 94 views
6

考慮下面的C++代碼,基本模板類數據成員在派生模板類中不可見?

template <typename Derived> 
struct A 
{ 
    bool usable_; 
}; 

template <typename Derived> 
struct B : A< B<Derived> > 
{ 
    void foo() 
    { 
     usable_ = false; 
    } 
}; 

struct C : B<C> 
{ 
    void foo() 
    { 
     usable_ = true; 
    } 
}; 

int main() 
{ 
    C c; 
} 

我得到的編譯錯誤:在成員函數void B<Derived>::foo()

template_inherit.cpp:12: error: 'usable_' was not declared in this scope.

這是爲什麼?任何好的解決方法

+0

這是什麼編譯器? – 2010-11-17 23:11:33

+3

'struct B:A < B>'wat。 – GManNickG 2010-11-17 23:14:54

+3

@GMan哈哈CRTP變相:) – 2010-11-17 23:18:34

回答

13

這是因爲usable_是一個非依賴名稱,所以在模板被解析時查找它,而不是查找實例化(知道基類時)。

不合格的名稱查找不會查找,並且從屬基類中永遠不會查找非從屬名稱。您可以使名稱usable_依賴如下,這也將擺脫不合格的名稱查找

this->usable_ = false; 

// equivalent to: A<B>::usable_ = false; 
A< B<Derived> >::usable_ = false; 

B::usable_ = false; 

所有這些都將工作的。或者你可以在派生類中使用using聲明聲明名稱

template <typename Derived> 
struct B : A< B<Derived> > 
{ 
    using A< B<Derived> >::usable_; 

    void foo() 
    { 
     usable_ = false; 
    } 
}; 

注意,在C不會有問題 - 它不僅影響B

+0

最後一個GotW談論它。唉,Herb Sutter通常寫得很好的以下解決方案沒有發生。 :( – wilhelmtell 2010-11-17 23:55:40

相關問題