2011-03-09 103 views
4

在基類中調用非模板成員函數時,可以使用using將名稱導入派生類,然後使用它。 對於基類中的模板成員函數,這也是可能的嗎?如何在模板基類中調用模板成員函數?

只是using它不(使用g ++ - 快照 - 20110219 -std =的C++ 0x)工作:

template <typename T> 
struct A { 
    template <typename T2> void f() { } 
}; 

template <typename T> 
struct B : A<T> { 
    using A<T>::f; 

    template <typename T2> void g() { 
    // g++ throws an error for the following line: expected primary expression before `>` 
    f<T2>(); 
    } 
}; 

int main() { 
    B<float> b; 
    b.g<int>(); 
} 

我知道明確前綴的基類,如

A<T>::template f<T2>(); 

工作正常,但問題是:是否可能沒有和使用簡單的聲明(就像f不是模板函數一樣)?

如果這是不可能的,有人知道爲什麼嗎?

回答

9

這個工程(雙關語意):this->template f<T2>();

所以確實

template <typename T> 
struct B : A<T> { 
    template <typename T2> void f() 
    { return A<T>::template f<T2>(); } 

    template <typename T2> void g() { 
    f<T2>(); 
    } 
}; 

爲什麼using不會在依賴模板的模板職能的工作很簡單 - 語法不在這種情況下允許所需的關鍵字。

+0

+1,而對於雙關語呻吟:) – dappawit 2011-03-09 05:03:42

+0

謝謝,但這兩種解決方案都不能實現y回答這個問題,因爲兩者都不是簡單地比首先說'A :: template f ()'。 – Lars 2011-03-09 05:09:24

+0

我覺得'這個'比較簡單,雖然這當然是一個味道問題。但它也允許虛擬功能按預期工作(雖然我認爲這不是問題)。 – dappawit 2011-03-09 05:13:46

0

我相信你應該使用:

this->A<T>::template f<T2>();

或:

this->B::template f<T2>();

相關問題