2010-09-10 139 views
2

爲什麼下面的代碼不能編譯以及如何使用基類中的函數?使用多態模板重載函數

template<typename K> struct Base 
{ 
    K foo() { return (K)0; } 
}; 

template<typename K> struct Extension 
: public Base<K> 
{ 
    K foo(int a) { return (K)a; } 
}; 

int main() 
{ 
    Extension<float> e; 
    e.foo(); 
    return 0; 
} 

編輯:好吧,我認爲這是隻與模板類發生...什麼是背後的設計決定從子類的重載版本隱藏了基類版本的想法?我的意思是,在同一個類中聲明這兩個函數都可以。

回答

3

Extension::foo正在隱藏Base::foo。您可以使用使用delaration把它帶回來:

template<typename K> struct Extension 
: public Base<K> 
{ 
    using Base<K>::foo; 
    K foo(int a) { return (K)a; } 
}; 

項目#33(「避免隱藏繼承的名稱」)的斯科特邁爾斯的「有效的C++」,是這個問題。

0

它看起來像Base :: foo()是私人的。

+0

這些結構撥打電話。 struct的默認訪問是公共的。 – Danvil 2010-09-10 16:43:34

+0

啊是的。 -1爲我自己。什麼是編譯器錯誤? – 2010-09-10 16:46:29

1

Extension的foo隱藏了基地的foo。

向Extension添加using子句可解決編譯錯誤。

template<typename K> struct Base 
{ 
    K foo(void) { return (K)0; } 
}; 

template<typename K> struct Extension 
: public Base<K> 
{ 
    using Base<K>::foo; 
    K foo(int a) { return (K)a; } 
}; 

int main() 
{ 
    Extension<float> e; 
    e.foo(); 
    e.foo(1); 
    return 0; 
} 
3

要麼添加使用聲明像其他的答案顯示或使用合格的名稱

e.Base<float>::foo();